c - C 中的 malloc() 行为

标签 c malloc

对于下面的 C 代码,当我只输入一个字符时,我希望最后一个 printf 打印“10,10”。相反,它打印“10,8”。为什么是input当我 malloc 10 字节时只有 8 字节?

char* input;
unsigned long inputLen = 10;

input = (char*) malloc(10 * sizeof(char));

printf("Input: ");
getline(&input,&inputLen,stdin);
printf("%lu,%d",inputLen,sizeof(input));

最佳答案

sizeof(input) 返回指针input的大小,即 8 个字节。

通过 C FAQ :

Q: Why doesn't sizeof tell me the size of the block of memory pointed to by a pointer?

A: sizeof tells you the size of the pointer. There is no portable way to find out the size of a malloc'ed block. (Remember, too, that sizeof operates at compile time, and see also question 7.27.)

如果你想跟踪input的容量,你需要使用一个单独的变量,或者在堆栈上将input声明为一个数组,然后将数组的大小除以数组中单个元素的大小。将容量保留为单独的变量几乎总是更容易。

关于c - C 中的 malloc() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41797365/

相关文章:

c - 二维数组中间的内存地址越界?

c - C中的浮点舍入

c++ - 要学习 C,我应该只使用我的 C++ 编译器和 IDE 吗?

c - 打印副本的第二个索引时复制字符指针内容的函数崩溃

c 指针作为输入

c - 使用 malloc 在运行时分配内存时出现段错误

c++ - 数据结构 - 选择排序方法

c - 使用 openssl 进行 Base64 解码的一个非常奇怪的错误

c++ - 在 return 语句中,结果周围的括号是否重要?

c - 自定义 malloc 实现的问题