Using malloc is giving me more memory than expected?

  • A+

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.


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: