Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Pointer confusion

I want to store a string in memory and read it later:

$$->desc.constant->base.id =  (char*)malloc(200);
sprintf($$->desc.constant->base.id, "%f", $1);
printf("->%s\n", $$->desc.constant->base.id); //LINE A
printf("->%i\n", $$->desc.constant); //LINE B

//SOME OTHER CODE

//Then, later on in a function call:

printf("%i", expr->desc.constant); // LINE D
printf("%s", expr->desc.constant->base.id); // LINE C

Although Line B and Line D show the same address, the printf in Line C fails with a Segmentation fault. What am I missing?

Any help would really be appreciated!

like image 979
Chris Avatar asked Jul 29 '26 08:07

Chris


1 Answers

printf("->%i\n", $$->desc.constant); //LINE B

That is invalid. As you show the line prior to it that constant is actually a pointer, you cannot treat it as if it were of type int. They don't necassarily have the same sizeof and alignment. Use the format used for void*. It will output memory addresses properly:

printf("->%p\n", (void*)$$->desc.constant); //LINE B
like image 137
Johannes Schaub - litb Avatar answered Jul 31 '26 22:07

Johannes Schaub - litb



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!