The problem with your solution is that you fail to allocate memory for *dst
.
Consider the first three lines of the code that needs to work:
char *str = NULL;
new_strcpy(&str , "string one");
new_strcpy(&str , str +7); // ***
From this, it is clear that:
new_strcpy()
needs to allocate memory for the result.
- When allocating
str
anew, new_strcpy()
needs to deallocate the previous str
to avoid leaking memory.
- To make line
***
above work, the deallocation has to happen after the allocation.
Here is a skeleton implementation to give you the idea. I implement the functions in terms of strcpy()
et al, but if calling the library function is not permissible, you can write your own loops (you already know how to do that).
#include <stdlib.h>
#include <string.h>
void new_strcpy(char** dst, const char* src) {
char* orig_dst = *dst;
*dst = malloc(strlen(src) + 1);
strcpy(*dst, src); /* replace with a loop if calling strcpy() is not permissible */
free(orig_dst);
}
void new_strcat(char** dst, const char* src) {
char* orig_dst = *dst;
*dst = malloc(strlen(*dst) + strlen(src) + 1);
strcpy(*dst, orig_dst); /* replace with a loop if calling strcpy() is not permissible */
strcat(*dst, src); /* ditto for strcat() */
free(orig_dst);
}
void new_free(char** dst) {
free(*dst);
*dst = NULL;
}
int main(int argc, char *argv[])
{
char *str = NULL;
new_strcpy(&str , "string one");
new_strcpy(&str , str +7);
new_strcat(&str , " two");
/* new_printf(&str , "%str !", s); */
puts(str );
new_free(&str);
return 0;
}
I leave implementing new_printf()
as an exercise for the reader. :-)