i have some trouble with a simple copy function:
void string_copy(char *from, char *to) {
while ((*to++ = *from++) != '\0')
;
}
It takes two pointers to strings as parameters, it looks ok but when i try it i have this error:
Segmentation fault: 11
This is the complete code:
#include <stdio.h>
void string_copy(char *from, char *to);
int main() {
char *from = "Hallo world!";
char *to;
string_copy(from,to);
return 0;
}
Thank you all
Your problem is with the destination of your copy: it's a char* that has not been initialized. When you try copying a C string into it, you get undefined behavior.
You need to initialize the pointer
char *to = malloc(100);
or make it an array of characters instead:
char to[100];
If you decide to go with malloc, you need to call free(to) once you are done with the copied string.
You need to allocate memory for to. Something like:
char *to = malloc(strlen(from) + 1);
Don't forget to free the allocated memory with a free(to) call when it is no longer needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With