Realloc () function failed

Why is this code not working?

char *x=malloc(100); x++; x=realloc(x, 200); 

I mean, is x a valid string pointer, just incremented by one?

+4
source share
4 answers

Think about what realloc does. How can a free pointer to address x+1 when malloc actually create a pointer to address x ?

In more specific terms, suppose you allocate 100 bytes at 0x1000. Now x incremented, indicating 0x1001. Then you call realloc at the new address. Since none of the malloc , calloc and realloc created 0x1001, the free (or equivalent code) used by the realloc call has no idea how to do anything with 0x1001; he cannot even understand how many bytes of memory he is occupying. He knows only about 100 bytes in 0x1000.

The basic idea of โ€‹โ€‹implementing malloc and friends is that you keep track of the assigned pointers and the number of bytes allocated. Then, when free is called later, a pointer to free displayed. If there is no link to this pointer passed to free , what else needs to be done except for the failure? This is more logical for me than assuming that you can continue to use a pointer, which may or may not be valid.

+2
source

See C-standard (C99, 7.20.3.4p3) for realloc and my emphasis:

void * realloc (void * ptr, size_t size);

If ptr is a null pointer, the realloc function behaves like a malloc function for the specified size. Otherwise , if ptr does not match the pointer previously returned by calloc, malloc, or realloc, or if space was freed by a call to the free or realloc function, the behavior is undefined .

In your case, x was returned by malloc , not x + 1 . Thus, your program invokes undefined behavior.

+7
source
 char *x=malloc(100); x++; x=realloc(x, 200); 

In the above code, the address indicated by pointer x changes before calling the realloc() function. This behavior is undefined in C.

+2
source

This is undefined behavior if you think you got a pointer from malloc() , which is incorrect.

Clearly, x was returned by malloc , and its value was changed before calling realloc() . Therefore, it shows undefined behavior.

+1
source

Source: https://habr.com/ru/post/1502276/


All Articles