Thread: Need help with program allocating memory

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    11

    Need help with program allocating memory

    For some reason the program crashes at the GetFiles function.Anyone willing to help?Thanks

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <dirent.h>
    
    
    void ReadDirectory(char **maindir);
    void GetFiles(char *directory,char ***filenames,int *number);
    
    
    int main()
    {
        int number,i;
        char *maindir = NULL,**mainfilenames = NULL;
    
    
        printf("Give the directory where the movies are: ");
        ReadDirectory(&maindir);
    
    
        GetFiles(maindir,&mainfilenames,&number);
    
    
        for(i=0;i<number;i++)
        {
            printf("%s\n",mainfilenames[i]);
        }
    
    
        system("PAUSE");
        return 0;
    }
    
    
    void ReadDirectory(char **maindir)
    {
        int c,size = 0;
        char *temp = NULL;
    
    
        *maindir = malloc((size+1));
        (*maindir)[size] = '\0';
    
    
        size++;
    
    
        while((c = getchar()) != EOF && c != '\n')
        {
            temp = realloc(*maindir,size+1);
    
    
            if(temp)
            {
                *maindir = temp;
                (*maindir)[size-1] = c;
                (*maindir)[size] = '\0';
    
    
                size++;
            }
            else
            {
                printf("Error (A) reallocating memory.\n");
                exit(1);
            }
        }
    
    
        temp = NULL;
        free(temp);
    }
    
    
    void GetFiles(char *directory,char ***filenames,int *number)
    {
        struct dirent *dent;
        DIR *dir;
        int size;
        char **temp;
    
    
        if((dir = opendir(directory)) == NULL)
        {
            printf("Can't open directory %s!\n",dir);
            exit(2);
        }
    
    
        size = 0;
        *number = 0;
    
    
        *filenames = malloc(*number+1);
        (*filenames)[*number] = malloc(size+1);
    
    
        (*filenames)[*number][size] = '\0';
    
    
        while ((dent = readdir(dir)) != NULL)
        {
            if (!strcmp(dent->d_name,".") || !strcmp(dent->d_name,".."))
            {
                continue;
            }
    
    
            temp = realloc(*filenames,*number+1);
    
    
            if(temp)
            {
                *filenames = temp;
    
    
                while(dent->d_name[size] != '\0')
                {
                    size++;
                    temp[*number] = realloc((*filenames)[*number],size+1);
    
    
                    if(temp[*number])
                    {
                        (*filenames)[*number] = temp[*number];
                        (*filenames)[*number][size-1] = dent->d_name[size-1];
                        (*filenames)[*number][size] = '\0';
                    }
                    else
                    {
                        printf("Error (C) reallocating memory.\n");
                        exit(1);
                    }
                }
            }
            else
            {
                printf("Error (B) reallocating memory.\n");
                exit(1);
            }
    
    
            (*number)++;
        }
    
    
        closedir(dir);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Instead of trying to deal with more than two levels of indirection, I suggest that you make use of some abstraction by declaring structs. For example, you could start with:
    Code:
    struct Movie
    {
        char *filename;
        /* movie name? etc */
    };
    
    struct MovieDirectory
    {
        char *filepath;
        struct Movie *movies;
        size_t movie_count;
    };
    This way, you can then declare:
    Code:
    void ReadDirectoryName(struct MovieDirectory *maindir);
    
    void ReadDirectoryContent(struct MovieDirectory *maindir);
    Note that file and path names usually have some known maximum length, and while path names might be long, the individual file name typically would be limited to say, 255 characters, so instead of using dynamic memory allocation, you could simplify with something like:
    Code:
    #define FILENAME_MAXLEN 255
    
    struct Movie
    {
        char filename[FILENAME_MAXLEN + 1];
        /* movie name? etc */
    };
    and then only use dynamic memory allocation for the dynamic array of movies. Since you observed the problem in GetFiles, this could well help avoid/fix the problem when you implement ReadDirectoryContent.

    By the way, instead of reallocating character by character read as in your ReadDirectory function, it would likely be more efficient to use fgets in a loop to read a block of characters until EOF or a newline is encountered, i.e., expand the memory allocated, read into the start of the newly allocated area, then check the newly read area for a newline and check if fgets returned a null pointer. Also, it pointless to free(temp) right after setting temp to NULL.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Feb 2017
    Posts
    11
    Thank you for your tips , some are helpfull to me since i didnt know if what i was doing had any point (temp = NULL , free(temp)).However i dont want to change my thinking of allocating memmory for more than a character , i want to keep it at that one char at a time (read it,allocate memory for it(realloc),store it untill the string has ended then allocate memory for another string and so on...)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Regarding allocating memory
    By monkey_c_monkey in forum C++ Programming
    Replies: 2
    Last Post: 08-29-2012, 10:06 PM
  2. allocating some memory
    By supaman in forum C Programming
    Replies: 7
    Last Post: 03-09-2006, 10:34 PM
  3. allocating memory?
    By SamuraiDave in forum C Programming
    Replies: 2
    Last Post: 09-21-2005, 02:45 PM
  4. allocating memory
    By viaxd in forum C Programming
    Replies: 2
    Last Post: 10-12-2003, 07:13 PM
  5. Allocating memory...
    By PsychoBrat in forum C++ Programming
    Replies: 2
    Last Post: 01-17-2003, 11:09 PM

Tags for this Thread