先前使用的C代码的新分段错误

use*_*492 2 c linux file-io segmentation-fault

此代码用于获取文本文件中的名称列表,并转换为电子邮件表单

所以凯特琼斯成为kate.jones@yahoo.com这个代码在linux mint 12上运行良好,但现在完全相同的代码在arch linux上给出了段错误.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  FILE *fp;
  fp = fopen("original.txt", "r+");
  if (fp == NULL )
  {
    printf("error opening file 1");
    return (1);
  }

  char line[100];
  char mod[30] = "@yahoo,com\n";
  while (fgets(line, 100, fp) != NULL )
  {
    int i;
    for (i = 0; i < 100; ++i)
    {
      if (line[i] == ' ')
      {
        line[i] = '.';
      }
      if (line[i] == '\n')
      {
        line[i] = '\0';
      }

    }

    strcat(line, mod);

    FILE *fp2;
    fp2 = fopen("final.txt", "a");

    if (fp == NULL )
    {
      printf("error opening file 2");
      return (1);
    }

    if (fp2 != NULL )
    {
      fputs(line, fp2);
      fclose(fp2);
    }

  }

  fclose(fp);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Arch Linux是一个相当全新的安装,可能是我还没有安装C需要的东西吗?

fkl*_*fkl 9

我认为问题是当你的原始字符串加上mod超过100个字符时.

当你调用strcat时,它只是将第二个附加到第一个字符串的字符串复制,假设第一个字符串中有足够的空间,这里似乎不是这种情况.

只需增加线的大小即可

char line[130]; // 130 might be more than what is required since mod is shorter
Run Code Online (Sandbox Code Playgroud)

使用strncat也好得多

你可以限制复制到dst的最大元素数量,否则,如果给定足够大的字符串,strcat 仍然可以超出大小而不会抱怨.

虽然strncat的一个注意事项是它不会终止带有null的字符串,即它自己的\ 0,特别是当它们比给定的n短时.所以在实际使用之前应该仔细阅读其文档.

更新:平台特定说明

添加的想法,纯粹巧合的是,它没有在薄荷上出现错误并在拱门上坠毁.在实践中,它正在调用未定义的行为,并且应该更快或更快地崩溃.这里没有特定的平台.