I have an exercise where I need to write a wrapper function for strcat. After it prints the string length (for debugging) it seg faults and I am not quite sure why. Any help would be greatly appreciated.
EDIT: I didn’t specify that the wrapper function is supposed to guarantee that it never goes outside of the bounds of memory allocated for destination. This is why I allocated only enough memory for “string” in destination and reallocating more in the Strcat() wrapper.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* Strcat(char* destination, const char* source);
int main(void)
{
(void)printf("This strcat cannot fail!\n");
char* destination = (char*)malloc(sizeof(char)*7);
destination = "string";
(void)printf("%s\n", destination);
Strcat(destination, " concatination");
(void)printf("%s\n", destination);
(void)printf("It works!\n");
free(destination);
return 0;
}
char* Strcat(char* destination, const char* source)
{
(void)printf("%d\n", (strlen(destination)+strlen(source))*sizeof(char));
if((sizeof((strlen(destination)+strlen(source)))+1) > sizeof(destination))
destination = (char*)realloc(destination, sizeof((strlen(destination)+strlen(source)))+1);
return strcat(destination, source);
}
This line:
overwrites the pointer returned from
malloc(3)so you lose that memory forever. You probably meant to copy that string, so usestrcpy(3)or something.