Question

I am trying to read a directory using the Dirent Header file in C.

I am having trouble storing the file names inside the given directory inside a char array.

the code is below.

char * FileNames;

while ( ( DirentPointer = readdir(DirectoryPointer) ) != NULL) {

    strcpy(&FileNames[Counter], DirentPointer -> d_name);

    Counter++;
}

When I run the application I am getting a segmentation fault. I think that the strcpy is faulting the application because of memory allocations.

Can anyone tell me how malloc and realloc can be used to dynamically add memory allocation to the FileNames Char *?

Was it helpful?

Solution

Your code would produce undefined behaviour or most probably crash. That's because FileNames is a pointer to a character, not to a memory buffer to copy your strings into and the function strcpy does not do bounds checking for the buffer being copied into. So strcpy will try to write into the memory you have not allocated for the purpose. You need to allocate memory to copy the file names first.

#define MAX_FILE_NUM 1000

char *FileNames[MAX_FILE_NUM] = {0}; // initialize to NULL
int Counter = 0;

while((DirentPointer = readdir(DirectoryPointer)) != NULL) {
    FileNames[counter] = malloc(strlen(DirentPointer->d_name) + 1); // + 1 for the null byte
    // check for NULL
    if(FileNames[i] != NULL) {
        strcpy(FileNames[i], DirentPointer->d_name);
        Counter++;
    }
    else {
        // handle the NULL case
        // maybe try malloc again 
    }
}

// after you are done with the FileNames

for(int i = 0; i < Counter; i++) {
    free(FileNames[i]);
    FileNames[i] = NULL;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top