Start New Discussion within our Software Development Community

Hi please find this simple program, not sure why realloc is not working and its causing memory leak.
But if calloc and malloc is used with little changes it works fine.

#include "string.h"
#include "stdio.h"
#include "stdlib.h"

char *mystrcat(char*, char*);
void main(void){
    char str1[] = "quick brown fox";
    char str2[] = "Jumps over the lazy dog";


    printf("%s", strcat(str1, str2));
}


char *mystrcat(char* str1, char* str2){
    
    char *newstr ;
    int i =  strlen(str1); 
    int newSize =  sizeof(char) * (strlen(str1)+strlen(str2)+1);  // new size of array

    if((str1 =  (char *)realloc((void *)str1, newSize)) == NULL){
        fprintf(stderr, "Error: Could not allocate desired size");
    }
    
    //str1 = newstr;
    

    while(*str2){
        str1[i++] = *(str2++);
    }

    str1[i] = '\0';

    printf("%s", str1);
    return str1;  // or newstr; both have same address. check def of realloc
}

The memory was not allocated to the string(str1) which was copied, pls find the working code below,

#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
char *mystrcat(char*, char*);
int main(void){
    char str1[] = "quick brown fox";
    char str2[] = "Jumps over the lazy dog";
    

    printf("%s", mystrcat(str1, str2));
}


char *mystrcat(char* str1, char* str2){
    
    char *newstr ;
    int i =  strlen(str1); 
    int newSize =  sizeof(char) * (strlen(str1)+strlen(str2)+1);  // new size of array

newstr = (char *)realloc(NULL, strlen(str1) +1);
strcpy(newstr,str1);
    if((newstr =  (char *)realloc((void *)newstr, newSize)) == NULL){
        fprintf(stderr, "Error: Could not allocate desired size");
    }
    
    //str1 = newstr;
    

    while(*str2){
        newstr[i++] = *(str2++);
    }

    newstr[i] = '\0';

    printf("%s", newstr);
    getch();
    return newstr;  // or newstr; both have same address. check def of realloc
}
This article has been dead for over six months. Start a new discussion instead.