Search code examples
crealloc

realloc() unable to reallocate memory


i am writing a file copy program,in which i faced difficulty regarding realloc(). Please look at the following snippet (which i write to understand the working of realloc()):-

int main(){
    char *p =(char *) malloc ( 10 ),*t;
    p = "this is";
    if (strlen (p)==7)
    {
        t = realloc ( p,14);
        if ( t==NULL)
        {
            printf ("no no\n");
        }
    }
    printf("%p\n%p\n%d",p,t,strlen(p));
    free (p);
    free (t);
    return 1;
}

output

no no      //because realloc () is unable to reallocate  the memory
00450357   //address of p
00000000   //address of t

so why realloc() is unable to reallocate the memory and assign it (its address) to t?

EDIT i am using Code Blocks in windows.


Solution

  • You have overwritten the value returned by malloc by address of a static string. Then realloc receives the address of the static string as parameter to reallocate.

    char *p =(char *) malloc ( 10 ),*t;
    p = "this is";
    t = realloc ( p,14);
    

    What you probably wanted is:

    char *p =(char *) malloc ( 10 ),*t;
    strcpy(p, "this is");
    t = realloc ( p,14);