【发布时间】:2014-02-27 09:14:39
【问题描述】:
我使用 malloc 创建了数组指针,并试图用文本文件中的字符串填充,但是当我运行程序时出现分段错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
char *filename = "textfile.txt";
int rows = 10;
FILE *fp;
char* line = NULL;
size_t length = 0;
ssize_t read;
//make a 10 line *char array
char **aPointer = (char**)malloc(sizeof(char*)*rows);
if ((aPointer = NULL))
{
printf("Memory error\n");
exit(1);
}
//open file
if ((fp = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "Error opening file");
exit(1);
}
//read line from file to array
int i = 0;
while(((read = getline(&line, &length, fp)) != -1) && (i<rows))
{
strcpy(aPointer[i], line);
i++;
}
return 0;
}
-分段错误(核心转储)-
如何填写数组?
【问题讨论】:
-
我怀疑显示的那些行是崩溃的直接原因(尽管它们可能是间接的)。有问题的请发short and complete program (a.k.a. a SSCCE)。
-
哦,学习如何使用调试器。如果你在调试器中运行你的程序,它将在崩溃的位置停止,你可以例如检查函数调用堆栈和变量的值。如果不出意外,请使用调试信息(gcc 的
-g标志)构建程序并在调试器中运行,然后将bt命令的结果发布到the GNU debugger。 -
没有足够的信息来回答这个问题,请用实际发生崩溃的代码来完成。
标签: c arrays pointers char malloc