我想读取一个文件并将其存储在列表中。我确实这样做了,但当我使用gdb时,我得到了这个错误:
#0 0xfeea5b41 in strcpy () from /lib/libc.so.1.
这是代码:
int
main (int argc, char *argv[])
{
/*declare and initialise variable */
char array[10][150], buffer[150];
//message =(char*)malloc(sizeof(char));
int i = 0;
FILE *fp;
fp = fopen (argv[1], "r");
if (fp == 0)
{
fprintf (stderr, "Input not validn");
exit (1);
}
/*stores and prints the data from the string */
int counter = 0;
while (fgets (buffer, 150, fp))
{
strcpy (array[i], buffer);
//printf(" %s",message[i]);
i++;
counter++;
}
fclose (fp);
return 0;
}
这里有几个错误。
-
如果存在超过10行,则会超出
array
,而strcpy
将尝试复制到无效位置。我想这就是错误的原因。 -
fopen
在出现错误时返回一个指针(因此NULL
(,而不是0。 -
您没有检查
fgets
的返回值;它在出错时返回CCD_ 6。 -
增加
counter
和i
似乎是多余的,因为它们都将具有相同的值。 -
您还没有
#include
d相关的包含文件,因此您的C编译器将无法获得正确的函数原型。您需要:#include <stdio.h>
、#include <stdlib.h>
和#include <string.h>
。您可以通过使用gcc -Wall
进行编译来了解这一点。