realloc and malloc functions

后端 未结 2 1492
遇见更好的自我
遇见更好的自我 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: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.

提交回复
热议问题