I am writing my own string copy function. The following works:
char *src, *dest;
src = (char *) malloc(BUFFSIZE);
//Do something to fill the src
dest = (char *) malloc(strlen(src) + 1);
mystringcpy(src, dest);
void mystringcopy(char *src, char *dest) {
for(; (*dest = *src) != '\0'; ++src, +dest);
}
But this doesn’t work:
char *src, *dest;
src = (char *) malloc(BUFFSIZE);
//Do something to fill the src
mystringcpy(src, strlen(src), dest);
void mystringcopy(char *src, size_t length, char *dest) {
dest = (char *)malloc(length + 1);
for(; (*dest = *src) != '\0'; ++src, +dest);
}
and I can’t understand why… Is allocating memory inside a called function a mistake?
You haven’t really said what “works” means, but I’m assuming you’re confused why
destisn’t being changed to the new memory back in the calling function.The reason is that in your
mystringcopyfunction, the parameterdestis a copy of the pointerdestin the calling function.You then assign that copy to a new buffer, do the copy, and then the copy goes away. The original is unchanged. You need to pass
destas a pointer (to a pointer).Also, I assume you wrote what you did from memory since it shouldn’t compile as is (bad dereference in the calling function). Here’s the fixed code:
Another method is to return the
destpointer:Keep in mind if length is smaller than the source buffer’s real length that you’ll overrun your destination buffer. See the comments for a solution, though this is left up to you.