Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: copy a char *pointer to another

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

like image 732
Francesco Avatar asked May 15 '26 01:05

Francesco


2 Answers

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.

like image 180
Sergey Kalinichenko Avatar answered May 17 '26 14:05

Sergey Kalinichenko


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.

like image 21
kaylum Avatar answered May 17 '26 15:05

kaylum