我正在尝试使用 strcpy 函数将一个字符串复制到另一个 char 指针变量中。但我总是遇到段错误。这是我的代码。
/* 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);
}
最佳答案
在复制到pch3
之前,您需要为其分配空间。使用 malloc
创建一个足够大的 char 数组,以在复制 之前容纳源字符串的元素。您当前正在做的是声明一个 char 指针而不是初始化它。因此,它指向的内存位置可以在任何地方——这意味着你可能不应该尝试写入它——这就是你得到段错误的原因。使用 malloc
将允许您分配一个可以安全写入的内存区域,这将解决您的问题(假设对 malloc
的调用成功)。您不能只是将数据写入随机内存位置而不会出现段错误和访问冲突。
关于c - C 中的字符串复制导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12432251/