Anonymous
Anonymous

Reputation: 145

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!

Upvotes: 0

Views: 191

Answers (3)

Sourav Ghosh
Sourav Ghosh

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, 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,

Upvotes: 6

Vlad from Moscow
Vlad from Moscow

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

Bathsheba
Bathsheba

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

Related Questions