使用malloc给我的内存比预期的多吗? [英] Using malloc is giving me more memory than expected?

查看:66
本文介绍了使用malloc给我的内存比预期的多吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正努力与malloc保持联系,到目前为止,在测试和试用它时,我大多得到意想不到的结果.

I'm trying to get to grips with malloc, and so far I'm mostly getting unexpected results when testing and playing around with it.

int main(int argc, char** argv)
{
    int size = 10;
    int *A;
    A = (int *)malloc(size * sizeof(int));
    for (int i = 0; i < 10000; i++)
    {
        A[i] = i;
    }
    for (int i = 0; i < 10000; i++)
    {
        printf("%d) %d\n", i, A[i]);
    }
}

例如,在上面的示例代码中,该代码运行无错误.即使我只分配了A来保存10 * int,所以我希望循环在遇到错误之前只能运行10次.如果我将循环增加到大约30-40k,则会遇到分段错误.但是,如果我将大小增加到循环数量,它将始终按预期工作.因此,我知道如何避免该错误.有点,我只是希望有人可能会足够友善地解释为什么会这样.

With this example code above for example, the code runs without an error. Even though I only allocated A to hold 10 * int, so I expected the loop to only run 10 times before hitting an error. If I increment the loop to about 30-40k instead, it then hits a segmentation error. However if I increase my size to the loop amount, it would always work like expected. So I know how to avoid the error.. kinda, I was just hoping someone might be kind enough to explain why this is.

事实证明,我不欣赏C不能检测到界限,Java和C ++对我的照顾太多了.我有未定义的行为,现在知道防止这些行为是我的工作.感谢所有回答的人.

Turned out I didn't appreciate that C doesn't detect out of bounds, I've been looked after way too much by Java and C++. I had undefined behavior and now know it's my job to prevent them. Thanks for everyone that replied.

推荐答案

C不需要对数组访问执行任何边界检查.它可以让您读/写超出的内容而没有任何警告或错误.

C isn't required to perform any bounds checking on array access. It can allow you read/write past that without any warning or error.

您通过读取和写入分配的内存末尾来调用未定义的行为.这意味着您的程序的行为无法预测.它可能会崩溃,它可能会输出奇怪的结果,或者(按照您的情况)可能会正常工作.

You're invoking undefined behavior by reading and writing past the end of allocated memory. This means the behavior of your program can't be predicted. It could crash, it could output strange results, or it could (as in your case) appear to work properly.

仅仅因为程序会崩溃并不意味着会崩溃.

Just because the program can crash doesn't mean it will.

这篇关于使用malloc给我的内存比预期的多吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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