Search code examples
cunixrealloc

realloc() abruptly aborts the C program


Kindly note that I have already gone through

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

but, I didnt find it helpful.

I want to dynamicaly create an array of strings, with filenames as the strings.

Here is my code :

#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;
}

and here is the output :

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

Initially for few filenemes it did fine, but suddenly it aborts with the above error.

Any help will be greatly appreciated.


Solution

  • Wrong reallocation.

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

    BTW: No need to differentiate memory allocation calls. Since the pointer is initialized to NULL, use realloc() the first and subsequent times.

    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 well points out code should check for problem return values. Further, fileanme should be free() in the end.