girlrockingguna
girlrockingguna

Reputation: 289

Crashing on strcpy, not sure why?

   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.

Upvotes: 7

Views: 14074

Answers (2)

programmer
programmer

Reputation: 602

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);

Upvotes: 1

ouah
ouah

Reputation: 145899

        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

Upvotes: 7

Related Questions