【问题标题】:realloc() abruptly aborts the C programrealloc() 突然中止 C 程序
【发布时间】:2023-03-24 03:21:01
【问题描述】:

请注意我已经通过了

Facing an error "*** glibc detected *** free(): invalid next size (fast)"

但是,我觉得它没有帮助。

我想动态创建一个字符串数组,以文件名作为字符串。

这是我的代码:

#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char* argv[])
{  
    DIR         *dir = NULL;
    struct dirent   *file = NULL;
    int         i = 0;
    unsigned short  len;

    if ( (dir = opendir(".") ) == NULL ) {
        if (errno != 0) {
            perror("Unable to open current directory");
            exit(EXIT_FAILURE);
        }
    }

    char    **filename = NULL;

    while ( (file = readdir(dir)) != NULL ) {

        if (i == 0) 
            filename = malloc(sizeof(char*)*(i+1));     
        else 
            filename = realloc(filename,i+1);


        filename[i] = strdup (file->d_name);
        printf("%s  ", filename[i] );
        i += 1;
    } 
    if ( errno != 0 ) {
        perror("Unable to read from the current directory");
        exit(EXIT_FAILURE);
    } 

    if (dir != NULL) {
        if (closedir(dir) == -1) {
            if (errno != 0) {
                perror("Unable to close the current directory");
                exit(EXIT_FAILURE);
            }
        }
    } 
    printf("\n");
    return 0;
}

这是输出

*** Error in `./a.out': realloc(): invalid next size: 0x00000000016d6050 ***
realloc.c  StackOverflow  a.out  num_ip_using_scanf.c  Aborted

最初对于少数文件名它做得很好,但突然它因上述错误而中止。

任何帮助将不胜感激。

【问题讨论】:

  • 一个问题是在reallocmalloc 调用之后,您没有检查filename 是否为NULL。
  • @PaulMcKenzie 是的,我应该检查一下,谢谢指出。
  • 文件名(通常)长于 1 或 2 个字符。您的 malloc 仅适用于 1 或 2 个字符。 malloc 实际上需要为文件名的全长,如包含在文件结构的 file->d_name 成员中。 dup 操作将字符复制到堆中,越过分配的区域,从而破坏堆。这就是导致崩溃的原因。请注意,程序中还有其他几个错误,但这是主要错误。

标签: c unix realloc


【解决方案1】:

错误的重新分配。

// filename = realloc(filename, i+1);
filename = realloc(filename,(i+1) * sizeof *filename);`

顺便说一句:无需区分内存分配调用。由于指针初始化为NULL,所以第一次和以后都使用realloc()

char **filename = NULL;
...
// if (i == 0) filename = malloc(sizeof(char*)*(i+1));     
// else filename = realloc(filename,i+1);
filename = realloc(filename,(i+1) * sizeof *filename);`

@PaulMcKenzie 很好地指出代码应该检查有问题的返回值。此外,fileanme 最后应该是free()

【讨论】:

  • 是的,这个解决方案效果很好。我实际上习惯于这样做:filename = realloc(filename,(i+1)*sizeof(char*));但是,现在根据您的解决方案,我知道我可以简单地取消引用指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多