Difference between malloc and realloc?

前端 未结 3 1839
死守一世寂寞
死守一世寂寞 2021-02-13 03:18

Suppose I\'ve two code samples for creating a integer array of 10 elements:

int *pi = (int*)0; 
realloc(pi,10);

and the other is the one that i

相关标签:
3条回答
  • 2021-02-13 04:02

    The first assignment is not legal, because the pointer you pass into realloc() must have previously been given to you through an allocation of some kind. (Furthermore, you're ignoring its return value, something you must never do with allocations!)

    malloc() is to create a buffer for something, of some fixed size. realloc() is to give back one buffer and get another of some (presumably) different size -- and it might give you back the same buffer you were using.

    0 讨论(0)
  • 2021-02-13 04:16

    C requires that the pointer passed to realloc must be a pointer obtained from malloc, calloc or realloc function call (or a null pointer).

    0 讨论(0)
  • 2021-02-13 04:17

    When NULL is passed, realloc is equivalent to malloc. The NULL call can be useful if you're re allocating in some kind of loop and don't want to have a special case the first time you allocate.


    While we're at it, the fairly standard ways to use malloc and realloc are:

    int* p;
    p = malloc(10 * sizeof(int)); //Note that there's no cast
    //(also, it could just be int* p = malloc(...);)
    
    int* np = realloc(p, 15 * sizeof(int));
    //Note that you keep the old pointer -- this is in case the realloc fails
    

    As a tangential aside: history is the main reason you see declarations and assignments on different lines. In older versions of C, declarations had to come first in functions. That meant that even if your function didn't use a variable until 20 lines in, you had to declare at the top.

    Since you typically don't know what the value of a variable not used for another 20 lines should be, you can't always initialize it to anything meaningful, and thus you're left with a declaration and no assignment at the top of your function.

    In C99/C11, you do not have to declare variables at the top of scopes. In fact, it's generally suggested to define variables as close to their use as possible.

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