Question

I need to write a strcat in C. I tried below things:

 char * c_strcat( char * str1, const char * str2)
 {

      char * ret = (char *) malloc(1 + strlen(str1)+ strlen(str2) );

     if(ret!=NULL)
     {
         strcpy(ret, str1);
         strcat(ret, str2);

     if(str1 !=NULL) free str1; // If I comment this everything will be fine 
       return ret;
     }

     return NULL;
 }     


 int main()
 {

 char * first = "Testone";
 char *second = "appendedfromhere";

 first = c_strcat(first,second);
 if(second !=NULL) free(second);

// I want to store the result in the same variable 

 }

It crashed whenever I free the str1 memory in the c_strcat function. If I don't free then the memory allocated for the first will be leaked (if I understood properly).

How to store returned value to same variable (first)?

Was it helpful?

Solution

From section 7.20.3.2 The free function of the C99 standard:

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

And str1 (aka first) was not allocated by one of the three dynamic memory allocating functions, causing the crash. Same for second also.

if don't free then the memory allocated for the first will be leaked(if am understood properly).

Memory will be leaked if malloc(), realloc() or calloc() is used and the memory is not free()d at a later point. As the string literal "Testone" is not dynamically allocated it must not be freed.

Note that the pointer NULL check prior to invoking free() is unrequired as free(), as described above, does nothing if the pointer argument is NULL.


Do I cast the result of malloc?

OTHER TIPS

"Testone" & "appendedfromhere" are string literals, constants. They weren't allocated using malloc(), calloc() or realloc(), so you cannot free them.

If you want to store the results to str1 (like strcat does) the memory needed for the concatenated string must be allocated externally. I.e. str1 (first) must be large enough to hold first + second., e.g. by:

char first[100] = "Testone";

Than inside your c_strcat you do not allocate nor free any memory but just write str2 at the end ('\0') into str1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top