Crashing on strcpy, not sure why?

10,196

Solution 1

        char *temp;
        strcpy(longest, temp);

strcpy is strcpy(dst, src) not strcpy(src, dst). The source is the parameter on the right, not the parameter on the left.

Moreover char *temp is not initialized when you pass its value to strcpy. You need to allocate memory for temp to hold the string you copy, for example using malloc

Solution 2

There are 2 errors.

1) You need to first "allocate" memory for char *temp;

Example:

char *temp;
temp = malloc(4); // Allocate 4 character space. 
                  // Ensure to include #include <stdlib.h>2)

2) strcpy signature is strcpy( dest, src ). In your code it is strcpy( src, dest ) whih is wrong.

Correct Example: strccpy(temp, longest);

Share:
10,196
girlrockingguna
Author by

girlrockingguna

Updated on June 26, 2022

Comments

  • girlrockingguna
    girlrockingguna almost 2 years
       if (strlen(shortest) > strlen(longest)) {
                char *temp;
                strcpy(longest, temp);
                strcpy(shortest, longest);
                strcpy(temp, shortest);
         } 
     }
    

    strcpy(longest, temp) --> is causing my program to crash. Here is a detailed crash report (I've included the proper header file, so it's not that. Also compiler warned me of using uninitialied temp variable...):

    Program received signal SIGSEGV, Segmentation fault.
    __strcpy_ssse3 () at ../sysdeps/i386/i686/multiarch/strcpy-ssse3.S:85
    85 ../sysdeps/i386/i686/multiarch/strcpy-ssse3.S: No such file or directory.