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

后端 未结 17 561
再見小時候
再見小時候 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:45

    C kindly let you shoot yourself in the head. You have just used random memory on the heap. With unforeseeable consequences.

    Disclaimer: My last real C programing was done some 15 years ago.

提交回复
热议问题