Using sizeof with a dynamically allocated array

2019-01-02 18:44发布

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,

标签: c sizeof
5条回答
美炸的是我
2楼-- · 2019-01-02 19:20

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).

查看更多
临风纵饮
3楼-- · 2019-01-02 19:22

You are asking for the size of a char* which is 4 indeed, not the size of the buffer. The sizeof operator can not return the size of a dynamically allocated buffer, only the size of static types and structs known at compile time.

查看更多
闭嘴吧你
4楼-- · 2019-01-02 19:24

sizeof doesn't work on dynamic allocations (with some exceptions in C99). Your use of sizeof here is just giving 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 memory pointed to is at least as big as you asked for, so there's no reason to care about the actual size it allocated.

Also, you've allocated 10 kB, not 1 kB.

查看更多
君临天下
5楼-- · 2019-01-02 19:28

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 is only working on the buffer variable.

查看更多
何处买醉
6楼-- · 2019-01-02 19:32

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.

查看更多
登录 后发表回答