user3126802
user3126802

Reputation: 429

Realloc Function not Working correctly?

Why does the following code output 4 twice, instead of 8 and 20? Thanks

int size = 0;
int *pointer;
pointer = malloc(2 * sizeof(int));
size = sizeof(pointer);
printf("%d", size);
int *temp = realloc(pointer, 5 * sizeof(int));
if (temp != NULL) //realloc was successful
{
    pointer = temp;
} else //there was an error
{
    free(pointer);
    printf("Error allocating memory!\n");
}
size = sizeof(pointer);
printf("%d", size);

Upvotes: 2

Views: 5720

Answers (2)

Taylor Brandstetter
Taylor Brandstetter

Reputation: 3623

sizeof is evaluated at compile time, not run time (except in the case of variable length arrays, an odd feature of C99). In this case you're taking the size of the pointer, which is 4 bytes. Even if you took sizeof(*pointer), that would be equivalent to saying sizeof(int)

I realize you're trying to tell the size of the dynamically allocated memory, but there is no standard way to do this. You should just keep track of it yourself, in your own code.

Upvotes: 4

John Kugelman
John Kugelman

Reputation: 362037

sizeof is a compile-time operator that tells you how much space a variable or a type takes up. The answer you get is a constant. In the case of a pointer, sizeof tells you how many bytes it takes to store a memory address. This is typically 4 bytes on a 32-bit platform and 8 bytes on a 64-bit one.

It does not tell you how much memory has been allocated by malloc(). As it turns out, there unfortunately is no standard function to tell you the size of an allocated memory block. You have to keep track of it yourself.

Upvotes: 9

Related Questions