Difference between malloc and realloc?

前端 未结 3 1848
死守一世寂寞
死守一世寂寞 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.

提交回复
热议问题