Using malloc is giving me more memory than expected?

前端 未结 3 1772
甜味超标
甜味超标 2021-01-22 23:12

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 arg         


        
相关标签:
3条回答
  • 2021-01-22 23:27

    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.

    0 讨论(0)
  • 2021-01-22 23:36

    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.

    0 讨论(0)
  • 2021-01-22 23:39

    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.

    0 讨论(0)
提交回复
热议问题