Alex Rivera | Logout

Using sizeof with a dynamically allocated array

Asked 2010-04-28T16:51:34.263
9

gcc 4.4.1 c89

I have the following code snippet:

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

 char *buffer = malloc(10240);
 /* Check for memory error */
 if(!buffer)
 {
    fprintf(stderr, "Memory error\n");
    return 1;
 }
 printf("sizeof(buffer) [ %d ]\n", sizeof(buffer));

However, the sizeof(buffer) always prints 4. I know that a char* is only 4 bytes. However, I have allocated the memory for 10kb. So shouldn't the size be 10240? I am wondering am I thinking right here?

Many thanks for any suggestions,

Edit
Report

2 Answers

3

No. buffer is a char *. It is a pointer to char data. The pointer only takes up 4 bytes (on your system).

It points to 10240 bytes of data (which, by the way, is not 1Kb. More like 10Kb), but the pointer doesn't know that. Consider:

int a1[3] = {0, 1, 2};
int a2[5] = {0, 1, 2, 3, 4};

int *p = a1;
// sizeof a1 == 12 (3 * sizeof(int))
// but sizeof p == 4
p = a2
// sizeof a2 == 20
// sizeof p still == 4

It's the main difference between arrays and pointers. If it didn't work that way, sizeof p would change in the above code, which doesn't make sense for a compile-time constant.

answered 2010-04-28T16:56:41.847
2

Replace your sizeof by malloc_usable_size (the manpage indicates that this is non-portable, so may not be available with your particular C implementation).

answered 2010-04-28T16:56:11.650

Your Answer