Search code examples
carraysdynamic-memory-allocation

C memory allocation not working as expected


I am new to dealing with pointers and memory allocation. I don't understand what am I doing wrong. This is my code:

#include <stdio.h>
#include <stdlib.h>

int main() {
     int* i;
     printf("Size of i:%d\n",sizeof(i));
     i = malloc(5 * sizeof(int));
     printf("Size of i:%d\n",sizeof(i));
     i[100] = 3;
     printf("Impossible i:%d\n",i[100]);
}

I compile it using gcc file.c. From my understanding, this should not have been compiled since i[100] is not allocated. Instead I get an output:

Size of i:8
Size of i:8
Impossible i:3

What am I missing here? Disregarding the impossible i, to my understanding the output of the first two lines should have been

Size of i:8
Size of i:40

Solution

  • From my understanding, this should not have been compiled since i[100] is not allocated.

    It' simply undefined behaviour to access out of bounds. For undefined behaviours, compilers may or may not issue diagnostics. There's no requirement from the language.

    Disregarding the impossible i, to my understanding the output of the first two lines should have been

    Size of i:8
    Size of i:40

    The sizeof operator on a pointer, unlike arrays, can't deduce the size of the memory block it's point to. It's always going to give the size of the pointer i.e. sizeof(i) == sizeof (int*).

    There's no way to deduce it from the pointer; you just have to keep track of it yourself. One way is to store the value 5 in a variable and if malloc succeeds, you know there's space for 5 int's.