c - 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 string: "hello". can please explain why so? unable identify error. can rectify error, , me working code. please!
your program invokes undefined behavior because you're passing pointer, not returned dynamic memory allocator family of functions, realloc()
.
according c11
, chapter §7.22.3.5, the realloc function, (emphasis mine)
if
ptr
null pointer,realloc
function behavesmalloc
function specified size. otherwise, ifptr
not match pointer earlier returned memory management function, or if space has been deallocated callfree
orrealloc
function, the behavior undefined. [...]
that said,
for hosted environment,
void main()
should betterint main(void)
, @ least.please see discussion on why not cast return value of
malloc()
, family inc
..
Comments
Post a Comment