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");更多推荐
发布评论