开发者

help me to understand about this simple malloc in C

Here is the code that i want to understand:

#include <stdio.h>
#include <stdlib.h>
#define MAX 100

int main()
{

    int *ptr = (int *)malloc(5 * sizeof(int)),i;

    for(i=0;i<MAX;i++)
    {
        ptr[i] = i;
    }

 开发者_运维百科   for(i=0;i<MAX;i++)
    {
        printf("%d\n",ptr[i]);
    }

    return 0;
}

My question: I allocated 5 * int size of memory but why it takes more than 5 ineteger? Thnx


You reserved space for 5 integers. For the other 95 integers, you're writing into space that is reserved for other purposes. Your program may or may not crash, but you should expect that it will fail one way or another.


It doesn't "take" more than 5 integers; you are just invoking undefined behavior. You can't expect the code to "succeed" even if you are seeing it work on your implementation.


It's not 'taking' more than 5 integers : you allocated 5 * sizeof(int) and invoke undefined behavior by accessing memory beyond this size.

There's no question as whether you should set MAX to 10, 1024 or 100000 : the code is fundamentally wrong, and the fact that it didn't fail when you ran it doesn't make it less wrong. Tools like valgrind may help you detect such mistakes.


  • You are allocating 5 integers, anything you write or read more than this is incorrect
  • OS protection boundaries are 1 page, which generally means 4k.
  • Even if you have allocated only 5 integers, you still have the rest of the page unprotected. That is how buffer overflows and many program misbehaviors happen

  • I am betting if your MAX is set to 1025, you will have seg fault (assuming this is your program)


C doesn't perform bounds checking on arrays. If you have a 5-element array, C will happily let you assign to arr[5], arr[100], or even arr[-1].

If you're lucky, this will merely overwrite unused memory and your program will work anyway.

If you're unlucky, you'll overwrite other variables in your program, the metadata for malloc, or the OS, and Bad Things will happen. Get used to seeing the phrase "segmentation fault".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜