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
}