realloc()如何工作?

Old*_*ool 4 c realloc

假设我已经使用了分配内存malloc(),如果我在我的代码中执行:

char *newline = realloc ( oldline , newsize );
// Assuming oldline is the pointer to which the starting address
// of the memory which malloc() has returned, is assigned and,
// say, newsize is integer having 100 value.
Run Code Online (Sandbox Code Playgroud)

现在我的问题是: -

  1. 是否有必要newline指向与oldline之前的初始地址相同的地址?
  2. 是这样,在这种情况下,oldline将被释放(隐式)并将newline负责内存寻址?
  3. 完成上述代码并完成工作后,我该怎么办才能释放内存

    free(newline);
    
    Run Code Online (Sandbox Code Playgroud)

    要么

    free(oldline);
    
    Run Code Online (Sandbox Code Playgroud)

    或两者?

hiv*_*ert 9

这取决于realloc成功与否.如果realloc成功则:

  1. 不!例如,如果没有足够的连续内存,oldline那么newline将会有所不同oldline.

  2. free(newline);因为oldline必要时已被释放.在realloc之后oldline应该被视为无效指针.

如果不成功.然后,你使用oldline好像什么也没发生,特别是你应该释放它.