In C, why do X and Y work but not Z?
//X
int num = 5;
int *ptr;
ptr = #
//Y
int *mptr = (int *)malloc(sizeof(int *));
*mptr = 5;
//Z
int* myptr;
*myptr = 5;
In Z, I declare a pointer and try to make it point to a number, but I get a segmentation fault. But it seems to me like I'm doing the same thing in Z as X and Y. In X I just use the variable num instead of the number 5 directly, and in Y I just use the heap to hold the variables instead of the stack. So how come X and Y work but Z doesn't?
//X
int num = 5;
int *ptr;
ptr = #
For the above, the int value "num" is allocated on stack, or in program data segment so it has an address. Lets pretend it was assigned by the compiler the address 0x12345678. You create an int* ptr. This also has address lets say 0x20000000. The address currently point to random data. We want to make the pointer at 0x20000000 point to the data value at 0x12345678, so that we can read the contents of 0x12345678 and get back the value 5... so we place 0x12345678 inside the storage space at 0x20000000 (we set ptr = &num).
//Z
int* myptr;
*myptr = 5;
For the second example, we only have 0x20000000 (myptr). Its a pointer and it currently pointing nowhere or anywhere. When we do *myptr = 5, we look at the address stored at 0x20000000. Its random so it may be 0xffff0000 lets use that example. It will then try and write the value 5 to this address (0xffff0000) which does not exist and causes the segfault.
So in your last example, the pointer exists, but it does not point anywhere valid, so when you try to write where it points, you either corrupt valid memory or cause a segment fault.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With