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

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

    Let me give you an analogy to why this "works".

    Let's assume you need to draw a drawing, so you retrieve a piece of paper, lay it flat on your table, and start drawing.

    Unfortunately, the paper isn't big enough, but you, not caring, or not noticing, just continue to draw your drawing.

    When done, you take a step back, and look at your drawing, and it looks good, exactly as you meant it to be, and exactly the way you drew it.

    Until someone comes along and picks up their piece of paper that they left on the table before you got to it.

    Now there's a piece of the drawing missing. The piece you drew on that other person's paper.

    Additionally, that person now has pieces of your drawing on his paper, probably messing with whatever he wanted to have on the paper instead.

    So while your memory usage might appear to work, it only does so because your program finishes. Leave such a bug in a program that runs for a while and I can guarantee you that you get odd results, crashes and whatnot.

    C is built like a chainsaw on steroids. There's almost nothing you cannot do. This also means that you need to know what you're doing, otherwise you'll saw right through the tree and into your foot before you know it.

提交回复
热议问题