#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!
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, therealloc
function behaves like themalloc
function for the specified size. Otherwise, ifptr
does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to thefree
orrealloc
function, the behavior is undefined. [...]
That said,
For a hosted environment, void main()
should better be int main(void)
, at least.
Please see this discussion on why not to cast the return value of malloc()
and family in C
..