-2

I am learning C in linux and using GCC compiler. I have a following piece of code to understand the pointers in C.

int main(void)
{   
     int n;
     /*long int z;*/
     int a=1025;
     int* p;
     //int* ptr=&n;
     p=&a;
     n=sizeof(double);
     //printf("\nAddress of n is =%p",&n);
     printf("\nsize of integer is %d",n);
     printf("\nAddress of a is =%p, value of a is= %d",&a,*p);
     printf("\nAddress of a is =%p, value of a is= %d",p,*p);
     printf("\nAddress of this location is is =%p, value at this location is=    %d",(p+1),*(p+1));
}

OUTPUT

size of integer is 8
Address of a is =0x7ffd56375f90, value of a is= 1025
Address of a is =0x7ffd56375f90, value of a is= 1025
Address of this location is is =0x7ffd56375f94, value at this location is= 8

for the last printf statement why the value comes as 8. shouldnt it be a garbage value?

5
  • To me, 8 is about as garbage as it gets :-) Nov 11, 2017 at 19:39
  • 8 is a nice, garbage value. Nov 11, 2017 at 19:39
  • Here this takes the value of 'n'. If I change the value of n, *(p+1) prints the value of n.
    – jafar ali
    Nov 11, 2017 at 19:41
  • @jafar ali no it is undefined behaviour - it can be anything. If you dereference the unallocated or uninitialized object. Nov 11, 2017 at 19:42
  • The code lacks #include <stdio.h>. Don't assume we know the library headers - post the Minimal, Complete, and Verifiable example that shows the problem. Nov 11, 2017 at 19:48

1 Answer 1

0

my compiler is giving this one for last printf

Address of this location is is =0xbfc283b8, value at this location is=    -1077771340

it's garbage. you are trying to access data from p+1 location, we don't know what is there at p+1, if that memory is reserved for someone else you may get segmentation fault also. So I think it's undefined behaviour if you de-reference unreserved memory.

1
  • I get value at this location is= 3472272 Nov 11, 2017 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.