Search code examples
cstringpointersrealloc

Why the realloc did not work properly in this case?


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char *func(char * str){


    int len;
    len=strlen(str)+3;
    str = (char *)realloc(str,len);
    return str;


}

void main(){

    printf("str:%s",func("hello"));

}

The final ans prints (null),instead of printing the string: "hello". Can anyone please explain why is it so? I am unable to identify any error. Can anyone rectify the error, and help me with a working code. Please!


Solution

  • Your program invokes undefined behavior because you're passing a pointer, which was not previously returned by dynamic memory allocator family of functions, to realloc().

    According to C11, chapter §7.22.3.5, The realloc function, (emphasis mine)

    If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. [...]

    That said,