Why is there no realloc () function in the standard C library without copying data?

For example, I want a function like this:

char *dst = (char*)malloc(512); char *src = (char*)malloc(1024); ... dst = (char*)realloc(dst, 1024); memcpy(dst, src, 1024); 

As you can see, I just want the realloc () function to expand the buffer size, but realloc () in the C library can copy data from the old address. So is there a function in any library, like what I want?

+3
source share
3 answers

realloc attempts to extend the buffer without copying, but can only do this if the extra space is free.

In your case, you just allocated space for src , and this memory block might use realloc space. In this case, he can select a larger block somewhere else and copy the data to this block.

+1
source

Why not just:

 free(dst); dst = malloc(1024); 

Also note that realloc can move a block and also resize it, so the old pointer returned by a previous call to malloc , calloc or realloc may no longer refer to the same piece.

+5
source

So, is there a function in any library, like what I want?

No no. How should the system distribute a piece of memory if there is no space?

eg. imagine that you are doing this:

 char *a = malloc(2); char *b = malloc(2); 

The allocated memory may now look like this:

  1 2 3 4 5 6 7
 -------------------------
 |  |  |  |  |  |  |
 -------------------------
 \ / \ / \ /        
  \ / \ / \ /
    vvv
  memory unused / memory
  for "a" internal for "b"
          memory piece

You are now doing realloc(a,10); . The system cannot simply expand the memory fragment for "a". It will fall into the memory used by "b", so instead it should find another place in memory that has 10 contiguous free bytes, copy 2 bytes from the old part of the memory and return the pointer to these new 10 bytes.

0
source

All Articles