Reputation: 145
#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!
Upvotes: 0
Views: 191
Reputation: 134406
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
..
Upvotes: 6
Reputation: 311176
You may realloc an object that was allocated dynamically. String literals have static storage duration and may not be changed. Any attempt to modify a string literal results in undefined behavior.
What you could do is the following
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *func( const char * str )
{
size_t len = strlen( str ) + 3;
char *tmp = realloc( NULL, len );
if ( tmp ) strcpy( tmp, str );
return tmp;
}
int main( void )
{
char *str = func( "hello" );
if ( str ) printf( "str: %s\n", str );
free( str );
}
The program output is
str: hello
Take into account that the call
realloc( NULL, len )
is equivalent to
malloc( len )
Upvotes: 1
Reputation: 234875
"hello"
is a read-only string literal. Its type is really a const char*
although compilers allow assignment to a char*
despite all the merry hell that this causes.
The behaviour on calling realloc
on such a pointer is undefined. So the compiler can do anything it likes. It might eat your cat.
Upvotes: 6