What is causing this strcpy segfault?
Question
Here is my code and it faults here strcpy(pSrcString,"muppet");
Well infact it does whenever I use strcpy.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *pSrcString = NULL;
char *pDstString = NULL;
/* muppet == 6, so +1 for '\0' */
if ((pSrcString = malloc(7) == NULL))
{
printf("pSrcString malloc error\n");
return EXIT_FAILURE;
}
if ((pDstString = malloc(7) == NULL))
{
printf("pDstString malloc error\n");
return EXIT_FAILURE;
}
strcpy(pSrcString,"muppet");
strcpy(pDstString,pSrcString);
printf("pSrcString= %s\n",pSrcString);
printf("pDstString = %s\n",pDstString);
free(pSrcString);
free(pDstString);
return EXIT_SUCCESS;
}
Solution
You have misplaced your parentheses in (pSrcString = malloc(7) == NULL)
. In that way, you are first checking the result of malloc(7)
against NULL
(which turns out to be false or 0
), and then assigns that to pSrcString
. Basically:
pSrcString = 0;
Well of course that is not going to give you a valid memory to let strcpy
write things to. Try this instead:
(pSrcString = malloc(7)) == NULL
Likewise for pDstString
.
Aside, if you just want to have a copy of the string, you can use the strdup
function. That allocates memory for you and takes care of calculating the length itself:
pSrcString = strdup("muppet");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow