当前位置: 动力学知识库 > 问答 > 编程问答 >

struct - Freeing an array of structures which has char pointers

问题描述:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct

{

int id;

char *name;

char *lastname;

} student_type;

typedef struct

{

student_type list[15];

} student_list_type;

void get_students(FILE *input,char *filename,student_list_type *student_list);

int main()

{

printf("Hello world!\n");

student_list_type std_list;

student_list_type *std_list_p=&std_list;

FILE *input;

get_students(input,"students.txt",std_list_p);

return 0;

}

void get_students(FILE *input,char *filename,student_list_type *student_list)

{

int i=0;

int j=0;

input=fopen(filename,"r");

printf("filename is %s",filename);

while(fscanf(input,"%d",&student_list->list[i].id)==1)

{

student_list->list[i].name=(char *) malloc(15);

student_list->list[i].lastname=(char *) malloc(15);

fscanf(input,"%s",student_list->list[i].name);

fscanf(input,"%s",student_list->list[i].lastname);

i++;

}

for(j=0; j<i+1; j++)

{

free(student_list->list[i].name);

free(student_list->list[i].lastname);

}

free(student_list->list);

fclose(input);

}

I think i am failing at freeing part of this code.I have learned that i should free elemenets first then whole array but i possibly learned wrong way.Anyways this code doesn't give error messages but simply crashes sometimes after getting all student list from txt.

网友答案:

First of all you don't check if your fopen succeeds, if it fails fscanf still tries to open the variable input but in this case that would be NULL.

And why do you declare "File * input;" in main? If you pass it in the next moment to your function "get_student". Why not declare it directly in the function?

This code is more fail safe

void get_students(char *filename,student_list_type *student_list)
{
    int i=0;
    int j=0;

    FILE * input;

    input=fopen(filename,"r");
    printf("filename is %s",filename);   

    if((input = fopen("students.txt","r")) == NULL)
    {
        fprintf(stderr, "\nFile could not be open\n");
    }
    else
    {
        while(fscanf(input,"%d",&student_list->list[i].id)==1)
        {
            student_list->list[i].name=(char *) malloc(15);
            student_list->list[i].lastname=(char *) malloc(15);
            fscanf(input,"%s",student_list->list[i].name);
            fscanf(input,"%s",student_list->list[i].lastname);
            i++;
           }

            for(j=0; j<i+1; j++)
            {
                free(student_list->list[i].name);
                free(student_list->list[i].lastname);
            }

            fclose(input);
        }
}

And at the end you don't need to free this

free(student_list->list);

Because student_list was not allocated on the heap.

分享给朋友:
您可能感兴趣的文章:
随机阅读: