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

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

    Do :

    int *p = malloc(2 * sizeof(*p)); // wrong (if type is something greater than a machine word)
    
    [type] *p = malloc(2 * sizeof([type])); // right.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 05:55

    The reason for the size given to malloc() is for the memory manager to keep track of how much space has been given out to each process on your system. These tables help the system to know who allocated how much space, and what addresses are free()able.

    Second, c allows you to write to any part of ram at any time. Kernel's may prevent you from writing to certain sections, causing protection faults, but there is nothing preventing the programmer from attempting.

    Third, in all likelyhood, malloc()ing the first time probably doesn't simply allocate 8 bytes to your process. This is implementation dependent, but it is more likely for the memory manager to allocate a full page for your use just because it is easier to allocate page size chunks....then subsequent malloc()'s would further divide the previously malloc()ed page.

    0 讨论(0)
  • 2020-12-03 05:57

    Simple logic: If you do not park in a legal parking space, nothing might happen but occasionally your car might get towed and you might get stuck with a huge fine. And, sometimes, as you try to find your way to the pound where your car was towed, you might get run over by a truck.

    malloc gives you as many legal parking spots as you asked. You can try to park elsewhere, it might seem to work, but sometimes it won't.

    For questions such as this, the Memory Allocation section of the C FAQ is a useful reference to consult. See 7.3b.

    On a related (humorous) note, see also a list of bloopers by ART.

    0 讨论(0)
提交回复
热议问题