可能我只是不了解malloc的工作原理,但我的代码没有出现错误:
int amount_integers = 2;
int *pointer_to_allocated_memory = (int*)malloc(amount_integers * sizeof(int));
for (int i = 0; i < amount_integers; i++)
{
int *address = &(pointer_to_allocated_memory)[i * sizeof(int)];
*(address) = 0;
}
我想为任意数量的整数初始化内存(
amount_integers
可能不是2)。然而,2号线的malloc似乎失灵了。MSVC的调试器将在此时中断(没有定义断点)。继续时,当*(address) = 0;
为1时,它将在第6行(i
)遇到访问写入冲突。我认为我正在访问的内容:
v pointer_to_allocated_memory[0 * sizeof(int)]
... | sizeof(int) | sizeof(int) |
^ pointer_to_allocated_memory[1 * sizeof(int)]
这些应该被分配。为什么应用程序会崩溃?
最佳答案
数组索引不是索引字节,而是数组元素,在您的情况下是:
int *address = &(pointer_to_allocated_memory)[i];
i
的有效值为0和1关于c - 为Int分配空间时,Malloc的行为异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23030506/