C malloc仅为int *分配了8个字节 [英] C malloc allocated only 8 bytes for int *

查看:99
本文介绍了C malloc仅为int *分配了8个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在函数中创建指向 6 元素 int 的指针,以便稍后将其返回,因此为此,我正在使用 malloc,但它似乎不符合我的预期.这是代码:

I'm trying to create a pointer to a 6 element int in a function to return it later, so for that purpose I'm using malloc, but it seems to be acting not as I expected. Here's the code:

int j = 0;
for (;j < 5; j++) {
    int * intBig = malloc(j * sizeof(int));
    printf("sizeof intBig - %ld\n", sizeof(intBig));
}

每次迭代打印与 sizeof(intBig)相同数量的 8 字节.而我期望一系列 4、8、12、16 .在这种情况下我想念什么?

Prints the same number 8 bytes as the sizeof(intBig) at each iteration. Whereas I would expect a series of 4, 8, 12, 16. What am I missing in this instance?

推荐答案

这是因为您要打印 int * 的大小.这样的指针总是具有相同的大小. sizeof 是一个编译器构造.它无法知道仅在运行时发生的事情,例如动态内存分配.会是

This is because you're printing the size of an int *. Such a pointer always has the same size. sizeof is a compiler construct. It cannot know things that only occur at runtime, such as dynamic memory allocation. Would it be something like

int intBig[100];

然后,您将获得数组的大小(以字节为单位),因为编译器知道数组的大小.但是 sizeof 运算符的结果始终是编译时常量¹,因此,您所拥有的内容不可能产生任何其他结果.

then you would get the size of the array back (in bytes), because the compiler knows how large it is. But the result of the sizeof operator is always a compile-time constant¹, so there is no way what you have there could yield anything else.

此外,那里还有内存泄漏,因为您没有免费重新存储您的内存.

Besides, you have a memory leak there because you're not free-ing your memory again.

¹可变长度数组(VLA)是一个例外,但此处未使用.

¹ Variable Length Arrays (VLA) are an exception, but they were not used here.

这篇关于C malloc仅为int *分配了8个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆