Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C malloc allocated only 8 bytes for int * [duplicate]

Tags:

c

malloc

I'm trying to create a pointer to a 6 element int in a function to return it later, so for that purpose I'm using malloc, but it seems to be acting not as I expected. Here's the code:

int j = 0;
for (;j < 5; j++) {
    int * intBig = malloc(j * sizeof(int));
    printf("sizeof intBig - %ld\n", sizeof(intBig));
}

Prints the same number 8 bytes as the sizeof(intBig) at each iteration. Whereas I would expect a series of 4, 8, 12, 16. What am I missing in this instance?

like image 887
Morgan Wilde Avatar asked Dec 01 '22 20:12

Morgan Wilde


1 Answers

This is because you're printing the size of an int *. Such a pointer always has the same size. sizeof is a compiler construct. It cannot know things that only occur at runtime, such as dynamic memory allocation. Would it be something like

int intBig[100];

then you would get the size of the array back (in bytes), because the compiler knows how large it is. But the result of the sizeof operator is always a compile-time constant¹, so there is no way what you have there could yield anything else.

Besides, you have a memory leak there because you're not free-ing your memory again.


¹ Variable Length Arrays (VLA) are an exception, but they were not used here.

like image 114
Joey Avatar answered Dec 03 '22 10:12

Joey