Hello,
just before my program exits I am trying to free up all malloced memory, however when I try to call free on one of my char * I get a segmentation fault. Here is some of my code.
Here is my structure....it is a linked list:
Here is how I add to my structure:
file_info is part of a another structure called word_structure.
This is where I allocate the memory for my char pointer:
So this means that my variable filename has been created from malloc right?
Now, here is how I free everything up:
Shouldn't calling free on header->filename where filename is a char pointer work?? I was calling malloc myself for the filename pointer but then I saw a book using strdup and thought maybe that was a better way.
Thanks for any help.
Later
just before my program exits I am trying to free up all malloced memory, however when I try to call free on one of my char * I get a segmentation fault. Here is some of my code.
Here is my structure....it is a linked list:
Code:
//this is a structure for our file information
struct file_info
{
char *filename;//name of the file
unsigned long matches;//number of matches for the file
// struct line_info *
struct file_info *next_file; //the next file
};
Here is how I add to my structure:
Code:
//this is for the file structure
void add_file(struct word *word_structure, char *line, char *filename, int line_num)
{
struct file_info *new_file_ptr;
//allocate our memory
new_file_ptr = malloc(sizeof(struct file_info));
if(new_file_ptr == NULL)
{
memory_error();
}
//printf("Adding file %s\n", filename);
new_file_ptr->filename = strdup(filename);
new_file_ptr->filename=filename;//set our file name
new_file_ptr->matches = 0;//initialize our matches to 0
//set the next_file to point to the current head
new_file_ptr->next_file = word_structure->files;
word_structure->files = new_file_ptr;//now set files to point to our new ptr
}
file_info is part of a another structure called word_structure.
This is where I allocate the memory for my char pointer:
Code:
new_file_ptr->filename = strdup(filename);
Now, here is how I free everything up:
Code:
void free_files(struct file_info *header)
{
struct file_info *next_file;
//let's loop through our file list and free up each one
while(1)
{
if(header == NULL)//we have run out of files
break;
//set our file list to point to the next file
next_file = header->next_file;
printf("Freeing %s\n", header->filename);
free(header->filename);//error occurs here!!
free(header);
header = next_file;
}
}
Shouldn't calling free on header->filename where filename is a char pointer work?? I was calling malloc myself for the filename pointer but then I saw a book using strdup and thought maybe that was a better way.
Thanks for any help.
Later