简体   繁体   中英

Memory Allocation C with pointers and structures

I'm trying to write to a pointer by accessing it and allocating memory from other function. But after a few iterations on the while statement, core dumped is thrown. I get the data from a file that it's ensured to be in the correct format.

It fails when there are still names to read from the file (checked with the debugger)

Main

Category *category = NULL;
memoryAllocate(&category);

Memory Allocation

memoryAllocate(Category **category){

 int elements;
 char name[NAME];
 int i = 0;
 FILE *fPeces;

  [...]

    //Get the number of elements from the file
    fscanf(fPeces, "%d", &elements);
    *category = (Category *)malloc(sizeof(Category) * elements));
    if(*category == NULL){
        //ERROR
    }
    else{

        while(i < elements){

            fgets(name, NAME, fPeces);
            strcpy(category[i]->categoryName, name);
            i++;

        }
}

Structure

typedef struct categoria {
    char categoryName[NAME];
    int part_num;
    Parts *parts;
} Category;

FILE (first number is the number of categories and the rest are the names)

6
category 1
category 2
category 3
category 4
category 5
category 6

You're derefencing the wrong thing in your while loop. This line:

strcpy(category[i]->categoryName, name);

Should be:

strcpy((*category)[i].categoryName, name);

Editorial notes:

  1. This problem is why I recommend minimizing the use of nested pointers where possible - it gets confusing fast. Instead of using *category all over the place, allocate that array locally:

     Category *myArray = malloc(elements * sizeof *myArray);

    Do your work with it:

     strcpy(myArray[i].name, name);

    And then only when you're done, copy that pointer into the output parameter:

     *category = myArray;
  2. while(.feof(... is always wrong .

  3. Don't cast the result of malloc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM