realloc and malloc functions

后端 未结 2 1493
遇见更好的自我
遇见更好的自我 2021-01-29 16:17

Look at the code:

#include


 #include
void main()
{
  int *p;
  p = malloc(6);
  p = realloc(p, 10);
  if (p == NULL)
  {
    pri         


        
相关标签:
2条回答
  • 2021-01-29 16:27

    As stated at the specification for realloc:

    If the new size of the memory object would require movement of the object, the space for the previous instantiation of the object is freed.

    0 讨论(0)
  • 2021-01-29 16:37

    Correct -- if realloc can't resize the memory block you pass in, it makes a new one, copies the data, and deallocates the old one.

    HOWEVER:

    1. malloc implementations do not typically operate on a byte granularity. Most of the ones I've seen round everything up to the nearest 16 bytes, since it makes accounting easier, and many users will need that alignment anyway. In your case, this would end up making the realloc a no-op, since both sizes round up to 16 bytes.

    2. In most common multitasking operating systems, the only memory accessible to your application is its own -- other applications' memory will never get in your way. Memory allocated by libraries or other threads might, though.

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