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

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

    Try this:

    int main ( int argc, char *argv[] ) {
      int *p = malloc(2 * sizeof *p);
      int *q = malloc(sizeof *q);
      *q = 100;
    
      p[0] = 10;    p[1] = 20;    p[2] = 30;    p[3] = 40;
      p[4] = 50;    p[5] = 60;    p[6] = 70;
    
    
      printf("%d\n", *q);
    
      return 0;
    }
    

    On my machine, it prints:

    50

    This is because you overwrote the memory allocated for p, and stomped on q.

    Note that malloc may not put p and q in contiguous memory because of alignment restrictions.

提交回复
热议问题