繁体   English   中英

将文件读入字符串数组C

[英]Reading a file into an array of strings C

我在将文件读入C中的字符串数组时遇到麻烦。这是我的代码:

  char mylittleBuffer[BUFFER_SIZE];     //BUFFER_SIZE is 4096
  char *a;
  char **c;

  fprintf(stderr, "LOL\n");
  for(int i = 0; (a = fgets(mylittleBuffer, sizeof(mylittleBuffer), myInput)) != NULL; i++)
    {
      fprintf(stderr, "a: %s\n", a);
      c[i] = malloc(sizeof(a));
      if (c[i] == NULL)
        printf("c[i] is NULL");
      c[i] = strdup(a);
      //      fprintf(stderr, "mylittleBuffer: %s\n", mylittleBuffer);                                                                                                                                                   
      fprintf(stderr, "c[i] %s\n", c[i]);
    }

看来只有一个行的文件是只读的程序将打印出a一次。 其他线路发生了什么? 我没有收到任何错误消息...

  1. 这是什么问题?
  2. 我该如何解决这个问题?

您尚未初始化c指向任何内容(您需要为其分配空间),因此,当您使用c[i] ,您正在使用未定义的内存位置,从而调用未定义的行为。 它不会崩溃是一个奇迹。 您将需要为字符指针数组分配空间。

enum { INITIAL_SIZE = 2 };            // Set to a larger number when not debugging
char mylittleBuffer[BUFFER_SIZE];     //BUFFER_SIZE is 4096
char *a;
size_t c_size = INITIAL_SIZE;
char **c = malloc(c_size * sizeof(*c));

if (c == NULL)
{
    fprintf(stderr, "out of memory (for c)\n");
    return;
}

fprintf(stderr, "LOL\n");
for (int i = 0; (a = fgets(mylittleBuffer, sizeof(mylittleBuffer), myInput)) != NULL; i++)
{
    fprintf(stderr, "a: %s\n", a);
    if (i >= c_size)
    {
         // Reallocate c to get more space
         size_t new_size = c_size * 2;
         void *new_space = realloc(c, new_size * sizeof(*c));
         if (new_space == 0)
         {
             // Release the already allocated c[i]
             // Release c
             fprintf(stderr, "Out of memory (for more c)\n");
             return;
         }
         c_size = new_size;
         c = new_space;
    }
    // c[i] = malloc(sizeof(a));  // Leak - you use strdup() too
    c[i] = strdup(a);
    if (c[i] == NULL)
    {
        fprintf(stderr, "c[i] is NULL\n");
        // Release the already allocated c[i] strings
        // Release c
        return;
    }
    //      fprintf(stderr, "mylittleBuffer: %s\n", mylittleBuffer);
    fprintf(stderr, "c[%d] <<%s>>\n", i, c[i]);  // <<>> show where the string ends
}

我大部分都保留了您的代码。 要不是我的, a也就不存在了, mylittleBuffer将只是buffer ,这就是我想要的循环体代替使用a 我可能会为c使用一个较长的名称,尽管我通常会使用比其他人更短的名称。

请注意,如果调用失败,使用realloc()的代码如何避免丢失指向先前分配的内存的指针。 如果将其直接分配给c ,则将丢失对先前内存分配的唯一引用-可能会导致重大泄漏。

鉴于需要两次清理代码,因此我将编写一个函数来执行此操作:

static void release_memory(size_t num, char **strings)
{
    for (size_t i = 0; i < num; i++)
        free(strings[i]);
    free(strings);
}

它将被称为:

release_memory(i, c);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM