c-如何修复/lib/libc.so.1中strcpy()中的#0 0xfeea5b41



我想读取一个文件并将其存储在列表中。我确实这样做了,但当我使用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;
}

这里有几个错误。

  1. 如果存在超过10行,则会超出array,而strcpy将尝试复制到无效位置。我想这就是错误的原因。

  2. fopen在出现错误时返回一个指针(因此NULL(,而不是0。

  3. 您没有检查fgets的返回值;它在出错时返回CCD_ 6。

  4. 增加counteri似乎是多余的,因为它们都将具有相同的值。

  5. 您还没有#included相关的包含文件,因此您的C编译器将无法获得正确的函数原型。您需要:#include <stdio.h>#include <stdlib.h>#include <string.h>。您可以通过使用gcc -Wall进行编译来了解这一点。

最新更新