Why do you specify the size when using malloc in C?

后端 未结 17 582
再見小時候
再見小時候 2020-12-03 05:19

Take the following code :

int *p = malloc(2 * sizeof *p);

p[0] = 10;  //Using the two spaces I
p[1] = 20;  //allocated with malloc before.

p[2] = 30;  //U         


        
17条回答
  •  生来不讨喜
    2020-12-03 05:53

    As everyone has said, you're writing to memory that isn't actually allocated, meaning that something could happen to overwrite your data. To demonstrate the problem, you could try something like this:

    int *p = malloc(2 * sizeof(int));
    p[0] = 10; p[1] = 20; p[2] = 30;
    int *q = malloc(2 * sizeof(int));
    q[0] = 0; // This may or may not get written to p[2], overwriting your 30.
    
    printf("%d", p[0]); // Correctly prints 10
    printf("%d", p[1]); // Correctly prints 20
    printf("%d", p[2]); // May print 30, or 0, or possibly something else entirely.
    

    There's no way to guarantee your program will allocate space for q at p[2]. It may in fact choose a completely different location. But for a simple program like this, it seems likely, and if it does allocate q at the location where p[2] would be, it will clearly demonstrate the out-of-range error.

提交回复
热议问题