Search code examples
cstringstrcpy

simple strcpy from string to string crashes entire programme


sorry if this is a commonly asked question but I'm not sure as to why this code will not output anything:

#include <stdio.h>
#include <string.h>

int main()
{
char source[] = "hello world!";

char **destination;

strcpy(destination[0], source);

puts(destination[0]);
puts("string copied!");

return 0;
}

it looks like it is crashing at strcpy() as "string copied!" does not appear in the terminal either


Solution

  • Your problem is that char **destination is an empty pointer to a pointer. destination[0] points to absolutely nothing.

    Here is how you would actually do it:

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
      char source[] = "hello world!";
    
      char destination[100];
    
      strcpy(destination, source);
    
      puts(destination);
      puts("string copied!");
    
      return 0;
    }
    

    Or if you want to determine the size of destination dynamically:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main()
    {
      char source[] = "hello world!";
    
      char *destination = malloc(strlen(source) * sizeof(char)+1); // +1 because of null character
    
      strcpy(destination, source);
    
      puts(destination);
      puts("string copied!");
    
    
      free(destination); // IMPORTANT!!!!
      return 0;
    }
    

    Make sure you free(destination) because it is allocated on the heap and thus must be freed manually.