Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 418
girlrockingguna Avatar asked Apr 13 '13 00:04

girlrockingguna


2 Answers

        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

like image 63
ouah Avatar answered Sep 30 '22 12:09

ouah


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

like image 36
programmer Avatar answered Sep 30 '22 12:09

programmer