cpointers

I just don't understand this pointer case


This is my code:

int *p;
p = 4;
printf("p is %p\n", p);
free(p);
// Need p=NULL, but I don't
int *q;
q = 5:
printf("q is %i", *q);

Then the error comes. I just need an explanation for it.


Solution

  • int *p;
    

    is a pointer to an int.

    p = 4;
    

    makes it point to the address 0x4.

    free(p);
    

    Try to deallocate the address 0x4.

    Basically, you are trying to free a resource that can not be freed.

    int *q;
    q = 5;
    

    points q to the address `0x5;

    *q;
    

    reads from the 0x5 address, which most likely will crash (also this address is not aligned).

    Pointers are not integers... the program you wrote shows a lack of understanding of what pointers are and why/how they should be used.