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 behaves malloc function specified size. otherwise, if ptr not match pointer earlier returned memory management function, or if space has been deallocated call free or realloc function, the behavior undefined. [...]

that said,


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -