将 sizeof 与动态分配的数组一起使用
gcc 4.4.1 c89
我有以下代码片段:
#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));
但是,sizeof(buffer) 总是打印 4。我知道 char* 只有 4 个字节。不过我已经分配了10kb的内存。那么大小不应该是10240吗?我想知道我是否在这里思考?
非常感谢您的任何建议,
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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您要求的是
char*
的大小,实际上是 4,而不是缓冲区的大小。 sizeof 运算符不能返回动态分配的缓冲区的大小,只能返回编译时已知的静态类型和结构的大小。You are asking for the size of a
char*
which is 4 indeed, not the size of the buffer. Thesizeof
operator can not return the size of a dynamically allocated buffer, only the size of static types and structs known at compile time.sizeof
不适用于动态分配(C99 中有一些例外)。此处使用sizeof
只是给出指针的大小。此代码将为您提供您想要的结果:如果
malloc()
成功,则指向的内存至少与您要求的一样大,因此没有理由关心实际< /em> 分配的大小。另外,您分配了 10 kB,而不是 1 kB。
sizeof
doesn't work on dynamic allocations (with some exceptions in C99). Your use ofsizeof
here is just giving you the size of the pointer. This code will give you the result you want: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.
如果需要,您可以自行跟踪内存的大小。 malloc 返回的内存只是指向“未初始化”数据的指针。 sizeof 运算符仅适用于 buffer 变量。
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.不。
buffer
是一个char *
。它是一个指向char
数据的指针。该指针仅占用 4 个字节(在您的系统上)。它指向 10240 字节的数据(顺便说一句,这不是 1Kb。更像是 10Kb),但指针不知道。考虑一下:
这是数组和指针之间的主要区别。如果它不这样工作,上面的代码中的 sizeof p 将会改变,这对于编译时常量来说没有意义。
No.
buffer
is achar *
. It is a pointer tochar
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:
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.将您的
sizeof
替换为malloc_usable_size
(联机帮助页表明这是不可移植的,因此可能不适用于您的特定 C 实现)。Replace your
sizeof
bymalloc_usable_size
(the manpage indicates that this is non-portable, so may not be available with your particular C implementation).