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

int main() {
  char tab[2]={"12"};
  FILE *outfile;
  char *outname = "/home/dir/";
  printf("%s", strcat(outname,tab));
  outfile = fopen(strcat(outname,btab), "w");
  if (!outfile) {
    printf("There was a problem opening %s for writing\n", outname);
  }
}

我有这个错误:分段错误。

我该如何解决?

4

4 回答 4

1

outname是字符串文字,字符串文字不可修改。修改字符串文字是未定义的行为。

于 2012-07-15T10:54:36.420 回答
1

至少有两个错误:

char tab[2] = {"12"};

你最好使用tab[3]甚至更好tab[]——你需要一个额外的字符作为终止 NUL 字符。

还,

char *outname = "etc...";

在可执行文件的数据段中创建一个常量字符串——它不能被覆盖,因为strcat它使用它的第一个参数来连接两个字符串。因此,当strcat()尝试这样做时,它会出现段错误。采用

char outname[50]; // something big enough
strcpy(outname, "/home/dir");

反而。

于 2012-07-15T10:57:56.003 回答
0

outname常量指针,所以一旦你在里面输入了一些东西,你就不能修改它。

However if you want to copy things in it, make a char array of the size equal to tab[] array because here the size of string to be copied is known. Most of the time char pointers like OUTNAME are used when you are taking input from a user once and you don't know how long that input will be.

于 2012-07-15T10:58:06.103 回答
0

In your code,

char *outname = "/home/dir/";

outname is a string literal and hence when used with strcat, it does not have enough length to hold the concatenated string.This results in segmentation fault.

Same is the case had you declared it as below,

char outname[] = "/home/dir/";

The solution for this to declare the size of the outname big enough to hold the concatenated string.

char outname[80] = "/home/dir/";
于 2015-07-13T15:47:53.763 回答