C中的字符串复制导致分段错误(String copy in C causing segmentation fault)

编程入门 行业动态 更新时间:2024-10-11 13:24:32
C中的字符串复制导致分段错误(String copy in C causing segmentation fault)

我试图复制一个字符串到另一个字符指针变量使用strcpy函数。但我总是得到分段fault.Here是我的代码。

/* strcat example */ #include <stdio.h> #include <string.h> int main() { char str[100]=""; char *pch3; strcpy(pch3,"Ravi"); //strcat(str,pch3); //Segmnetation fault. puts(pch3); return 0; }

如果我在这一个做同样的事情,我仍然是分段错误。

else { misc_rec_cnt++; fp1=fopen("breast-cancer-wisconsin-miscellaneous.data","a"); fprintf(fp1,"%s",line2); fclose(fp1); fp2=fopen("missingSCNs.data","a"); pch2=strtok(line2,","); fprintf(fp2,"%s\n",pch2); fclose(fp2); //pch3=(char *)malloc(sizeof(char)*strlen(line3)); pch3 = strtok(line3,","); while(pch3!=NULL) { if(strcmp(pch3,"?") == 0) { strcat(str1,"0"); strcat(str1,","); } else { //strcat(str1,pch3); strcat(str1,","); } pch3 = strtok(NULL,","); } strlen1=strlen(str1); memcpy(str2,str1,strlen1-1); fp3=fopen("breast-cancer-wisconsin-miscellaneous-cleansed.data","a"); fprintf(fp3,"%s\n",str2); fclose(fp3); }

I am trying to copy a string into another char pointer variable using strcpy function.But I always get segmentation fault.Here is my code.

/* strcat example */ #include <stdio.h> #include <string.h> int main() { char str[100]=""; char *pch3; strcpy(pch3,"Ravi"); //strcat(str,pch3); //Segmnetation fault. puts(pch3); return 0; }

If I do the same thing in this one I still get segmentation fault.

else { misc_rec_cnt++; fp1=fopen("breast-cancer-wisconsin-miscellaneous.data","a"); fprintf(fp1,"%s",line2); fclose(fp1); fp2=fopen("missingSCNs.data","a"); pch2=strtok(line2,","); fprintf(fp2,"%s\n",pch2); fclose(fp2); //pch3=(char *)malloc(sizeof(char)*strlen(line3)); pch3 = strtok(line3,","); while(pch3!=NULL) { if(strcmp(pch3,"?") == 0) { strcat(str1,"0"); strcat(str1,","); } else { //strcat(str1,pch3); strcat(str1,","); } pch3 = strtok(NULL,","); } strlen1=strlen(str1); memcpy(str2,str1,strlen1-1); fp3=fopen("breast-cancer-wisconsin-miscellaneous-cleansed.data","a"); fprintf(fp3,"%s\n",str2); fclose(fp3); }

最满意答案

pch3是未分配的指针,因此您正在将数据写入不存在的位置。 你的意思是把它分配给str ?

char str[100]=""; char *pch3; pch3 = str; strcpy(pch3,"Ravi");

pch3 is an unallocated pointer, so you're writing data to a location that doesn't exist. Did you mean to assign it to str?

char str[100]=""; char *pch3; pch3 = str; strcpy(pch3,"Ravi");

更多推荐

本文发布于:2023-07-26 06:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1271987.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   错误   String   copy   segmentation

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!