简体   繁体   中英

Issue with char pointer being assigned to another location and using strcpy()?

Here i'm trying to replace the word "how are you" in string array 's' by "woo". But it is exiting abruptly during the runtime . please help

char *s[] = {"hi there","how are you","Fine Ok!"};
char str1[4] = "how" ;char str2[4] = "woo";
char *j = NULL; //(char *)malloc(100*sizeof(char));
int i,k; char n[100] = "hi";
//printf("%d",strlen(s));
for(i = 0;i<3;i++ )
{
    j = strstr(s[i],str1);
    if(j==0)
    continue;
    else
    {
        printf("j is %s",j);
        printf("j is %s",j+10);
        strcpy(j,str2);

        printf("j is %s",j);
        break;
    }
}
printf("%s",s[1]);
return 0;

You have multiple problems in your code. Lets start with one of the more obvious: Remember that strcpy adds the string terminator. You might want to use memcpy instead:

memcpy(j, str2, strlen(str2));

To continue, you allocate memory and assign it to j , then in the loop you reassign to j making j point somewhere else, and you loose the original memory you have allocated leading to a memory leak. Also, in C you should not cast the result of malloc .

Lastly, and the probable cause of your crash: You try to modify a string literal, and all string literals are read only .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM