Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf and the p conversion specifier

In the C11 specification is said that argument type of %p must be void ** in case of scanf() function but I can't figure how to input an address and store it into a void **. Infact if I try to make:

void **p;
scanf("%p", p);

I get a segmentation fault.

P.S. C11 specification:

The corresponding argument shall be a pointer to a pointer to void

like image 545
xdevel2000 Avatar asked May 24 '26 03:05

xdevel2000


2 Answers

void **p;
scanf("%p", p);

doesn't work for the same reason that

int *i;
scanf("%i", i);

doesn't work - you're writing to an uninitialized pointer (or telling scanf to write to one, at least).

This works:

int i;
scanf("%i", &i);

and so does this:

void *p;
scanf("%p", &p);
like image 116
user253751 Avatar answered May 26 '26 15:05

user253751


NOTE: Original post did not have a mention for c11 standard.

Well, as per the c99 specification document, chapter 7.19.6. 1 2, paragraph 8 12,

p

Matches an implementation-defined set of sequences, which should be the same as the set of sequences that may be produced by the %p conversion of the fprintf function. The corresponding argument shall be a pointer to a pointer to void. The input item is converted to a pointer value in an implementation-defined manner. If the input item is a value converted earlier during the same program execution, the pointer that results shall compare equal to that value; otherwise the behavior of the %p conversion is undefined.

So, it is not void **, rather , a void *.

Next, Your reason for a segmentation fault is the use of uninitialized pointer p in scanf(). You did not allocate memory to p before using [passing it to scanf() as argument] it.

As others' suggested, you can nicely use something like

void *p;
scanf("%p", &p);

here, the &p value is actually pointer to a pointer to void and have a defined address.

like image 20
Sourav Ghosh Avatar answered May 26 '26 15:05

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!