Search code examples
cmemory-managementrealloc

I am getting Aborted (core dumped) in below code


Hi in my below code for testing realloc() I am getting the error Aborted (Core dumped).

The output of the code is below

$ ./realloc
My Name // <<-- This works
Aborted (core dumped) // <<-- why this error occur?

calling to copyThis() function 1st time gives the correct result and produce no error. In the same way if I call copyThis() for the second time, it make error. I can not understand why is it happening. Can any body point me out where the problem is and what the tweak should I do?

The code is below

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *copyThis(char *str1, const char *str2, size_t size);

int main(void)
{
    char *ptr1 = "My Name ";
    char *ptr2 = "is Alice";
    char *ptr3;
    char *ptr4;

    ptr3 = copyThis(ptr3, ptr1, strlen(ptr1) + 1); // This works
    printf("%s\n", ptr3);

    ptr4 = copyThis(ptr4, ptr2, strlen(ptr2) +1); // this line make Aborted (core dumped)
    printf("%s\n", ptr4);
}

char *copyThis(char *str1, const char *str2, size_t size)
{
    str1 = (char *) realloc(str1, size);
    strncat(str1, str2, strlen(str2));
    str1[size] = '\0';
    return str1;
}

NOTE : Please point me any good tutorial site that can help me catch string operations well in c/


Solution

  • str1[size] = '\0';
    

    writes beyond the allocated memory, thus your program crashes. You should allocate one more for the 0 character.

    The other error is that you call your function fro char* as first argument (ptr3 and ptr4) that are not initialized. This has undefined behavior, anything can happen with such code.

    A proper way would be to check if that argument is 0 and then just call malloc with the appropriate size. But for such an approach to work you would have to properly initialize these variables with 0, which you should do, anyhow.

    Also, don't cast the return of malloc and relatives, this might hide subtle bugs.