-3

The essence of what I'm trying to accomplish is the following. I want to pass in an address of integer (integer pointer) which is in form of a string to a function expecting an integer pointer as an argument. In terms of simple code, I want to do the following:

void dsp(int *);

int main() {

  char *b;
  int a=2;p=&a;
  b = (char *)malloc(100*sizeof(char));
  sprintf(b, "%p",p);
  puts( b );
  dsp(&a);
  dsp((int *)strtol(b,16));
  free(b);
return 0;
}

void dsp(int *addr)
{ 
  printf("val:%d\n",*addr);
}

And this is what my output is:

0x7fbffffa6c   (from puts(b))
val:2
Segmentation fault

Can anybody suggest what is wrong with above and/or how to go about it? Any help would be appreciated. Thank you.

cHao
  • 84,970
  • 20
  • 145
  • 172
user967850
  • 31
  • 6

3 Answers3

2

Using strtol for a pointer isn't a very portable idea since a long is not required fit a pointer. The simplest way to do what you're looking for would probably be to just replace it with sscanf which has an actual pointer format you can use;

dsp(&a);
int* recovered_pointer;
sscanf(b, "%p", &recovered_pointer);
dsp(recovered_pointer);

As a side note, you're not passing all 3 required parameters to strtol, which would not work even if long were "long enough" to fit the pointer. It's always a good idea to include the required header files, since they'll in this case help the compiler tell you at compile time that your code will break.

Community
  • 1
  • 1
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
1
dsp((int *)strtol(b,16));

First, you're missing a parameter here. strtol() takes three parameters. You're probably getting a compiler warning. Don't ignore those! If you add the proper #include at the top of your source file then the warning will turn into an error (which is a good thing):

#include <stdlib.h>

Second, you'll need to store the result of strtol() in a variable so that you can take the variable's address. You can't take the address of a function's return value. Adding a (int *) cast in front doesn't do it (although it does strong arm the compiler into accepting the bad code).

int result;
result = (int) strtol(b, NULL, 16);
dsp(&result);
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

Here's working code tested with 32- and 64-bit VS2012 compiler:

#include <stdlib.h>
#include <stdio.h>

void dsp(int*);

int main()
{
    char *b;
    int* t;
    int a = 2;
    b = malloc(100 * sizeof(char));
    sprintf(b,"%p", &a);
    dsp(&a);
    sscanf(b,"%p",&t);
    dsp(t);
    free(b);
    return 0;
}

void dsp(int* addr)
{
    printf("val:%d\n", *addr);
}
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251