Assigning value to pointer without allocating memory (C)?

When I tried the following code:

int *no_alloc_i;
*no_alloc_i = 3;
printf("%d\n", *no_alloc_i);

my code crashed, as expected. I believe that is because I did not allocate memory dynamically to no_alloc_i (correct me if I am wrong), because doing so makes the main function return 0 and the code works as expected:

int *alloc_i = (int*)malloc(sizeof(int));
*alloc_i = 3;
printf("%d\n", *alloc_i);

Afterwards, I tried allocating memory to alloc_i, did not allocate memory to no_alloc_i and then assigned a value to no_alloc_i:

int *alloc_i = (int*)malloc(sizeof(int));
int *no_alloc_i;
*no_alloc_i = 3;
printf("%d\n", *no_alloc_i);

The problem is that the pointer no_alloc_i that I had not allocated memory to was capable of holding a value. I do not understand how allocating memory to another variable could influence the behavior of the first variable. Thank you in advance!

>Solution :

Undefined behavior. It cannot (and shouldn’t be attempted to) be understood. The thing is, you just didn’t assign any value to your pointer so it was uninitialized, i.e. holding a semi-random unpredictable value. If that value happens to be an address inside a memory region that’s writable, using that spot in memory will "succeed" but corrupt something else because it’s not your memory. If it’s an address where no writable memory is allocated, you’ll crash attempting to access the memory there.

Leave a Reply