c - realloc() 突然中止 C 程序

标签 c unix realloc

请注意,我已经完成了

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

最初对于几个文件素它表现得很好,但突然它因上述错误而中止。

任何帮助将不胜感激。

最佳答案

错误的重新分配。

// 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()

关于c - realloc() 突然中止 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25497453/

相关文章:

linux - 使用 awk 变量删除文件

c - 为什么我会收到 "corrupted double-linked list"错误?

c - 尽管不包含 header ,函数仍会运行

c - 警告 : ‘return’ with a value, 在返回 void return next 的函数中; ex19.c:95:10: 错误:void 值没有被忽略,因为它应该被忽略

Shell 脚本 : find maximum value in a sequence of integers without sorting

c - 虚拟内存系统

使用 char 的 realloc 的 C 动态分配**

c - 内部 realloc() 的未定义行为

c - 在先前 malloc ed 指针上使用 realloc 会导致段错误

在 Mac OS X 上编译和链接 libev