Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is causing this strcpy segfault?

Tags:

c

malloc

strcpy

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;
}
like image 513
DannyK Avatar asked Mar 17 '26 09:03

DannyK


1 Answers

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");
like image 56
Lekensteyn Avatar answered Mar 19 '26 01:03

Lekensteyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!