user13377488
user13377488

Reputation:

Allocation with realloc

I am trying to list the subdirectory files of a specific directory. However, I receive an error "realloc(): invalid next size". I am using realloc(), cause further, I am gonna sort the array(by time modified, by lex...)

    DIR *dir2=NULL; 
    DIR *dir1; 
    struct dirent *sd;     
    struct dirent *ptr; 
    char **arr2=malloc(sizeof(char *)); 
    int size=0; 

    dir1=opendir(directory);  //current dir 
    while((sd=readdir(dir1))!=NULL) 
    { 
        if(sd->d_type==DT_DIR){  //checking,is it a dir? 
            dir2=opendir(sd->d_name);  //parent dir 
            printf("\n./%s\n",sd->d_name);  //printing parent directory's name 

            while((ptr=readdir(dir2))!=NULL){ 
                if(size>0){ 
                    arr2=realloc(arr2,(size)*sizeof(char*)); 
                    arr2[size]=malloc(50); 
                } 
                arr2[size]=ptr->d_name; 
                size++; 
            } 

            for(int i=0;i<size;i++) 
            { 
                printf("%s ",arr2[i]);  //listing files and directories. 
            }      
        } 
    } 

Yeah, you can not see free() in my code, in my real code I am doing free(), so the problem is in realloc (I guess).

Upvotes: 1

Views: 73

Answers (1)

Hitokiri
Hitokiri

Reputation: 3689

int size=0; 

At the beginning of program, you initialize the size equal to ZERO.

The first time your code reachs the realloc function at:

arr2=realloc(arr2,(size)*sizeof(char*));

the value of size is equal to 1. So, now the arr2 is allocated only for ONE pointer char *. Then you try to access the second value of arr2:

arr2[size]=malloc(50); // here, size  = 1

You have to change the malloc function to:

arr2=realloc(arr2,(size+1)*sizeof(char*));

It's safer to check the return value of mallocor realloc function. Because sometimes, it gets failed, then make your program runs not well.

Upvotes: 1

Related Questions