Using malloc is giving me more memory than expected?

谁都会走 提交于 2019-12-02 01:55:21

问题


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]);
    }
}

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.

Edit: 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.


回答1:


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.




回答2:


The codes runs without an error, but it is still wrong. You just do not notice it. Your loop runs out of the allocated area, but the system remains unaware of that fact until you run out of a much larger area your program can potentially access.

Picture it this way:

<UNAVAILABLE><other data>1234567890<other data><UNAVAILABLE>

Your 10 ints are in the middle of other data, which you can read and even write - to very unpleasant effects. C is not holding your hand here - only once you go out of the total available memory, the program will crash, not before.




回答3:


Undefined behavior doesn't mean "guaranteed segmentation fault"; it may work in some cases.

There is no way of knowing how far beyond an array's bounds you can go before you finally crash; even dereferencing one element beyond a boundary is undefined behavior.

Also: if malloc succeeds, it will allocate at least as much space as you requested, possibly more.



来源:https://stackoverflow.com/questions/54114574/using-malloc-is-giving-me-more-memory-than-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!