Using sizeof with a dynamically allocated array

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, sizeof (buffer) always prints 4. I know that char * is only 4 bytes. However, I have allocated memory for 10kb. So the size should not be 10240? I wonder if I think here?

Thanks so much for any suggestions,

+8
c sizeof
Apr 28 '10 at 16:51
source share
5 answers

You are requesting a char* size that is really 4, not a buffer size. The sizeof operator cannot return the size of a dynamically allocated buffer, but only the size of the static types and structures known at compile time.

+14
Apr 28 2018-10-18T00:
source share

sizeof does not work with dynamic allocations (with some exceptions on C99). Your use of sizeof here just gives you the size of the pointer. This code will give you the result you want:

 char buffer[10240]; printf("sizeof(buffer) [ %d ]\n", sizeof(buffer)); 

If malloc() succeeds, the specified memory is at least as large as you requested, so there is no reason to care about the actual size that it allocated.

In addition, you allocated 10 kB, not 1 kB.

+9
Apr 28 '10 at 16:53
source share

It is up to you to track the size of the memory if you need it. The memory returned by malloc is only a pointer to "uninitialized" data. The sizeof operator only works with the buffer variable.

+3
Apr 28 2018-10-18T00:
source share

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

It points to 10,240 bytes of data (which, by the way, is not 1Kb. More like 10Kb), but the pointer does not know this. 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 

This is the main difference between arrays and pointers. If this does not work, sizeof p will change in the above code, which does not make sense for the compile-time constant.

+3
Apr 28 2018-10-18T00:
source share

Replace sizeof with malloc_usable_size (the manpage indicates that this is not portable, therefore it may not be available with your specific C implementation).

+2
Apr 28 2018-10-18T00:
source share



All Articles