I have written a get_line function to read lines from a file. The file contains dictionary phrases and defintion file names separated by a ";". I have also written a read_ index function that reads form the file a line using get_line then splits the line up into it's needed parts and then inserts the 2 parts into a BST. For the last 2 weeks, I have not been able to get this to work on my school server, although it works fine on my home pc. Is there anyone that can help me spot the bug? I am totally exhausted and have tried over 15 different configurations to quell the problem with no success. Here is the code, I suspect the problem may lye in freeing the buffer after it is used...
Please HeLp Me!
Code:
char *get_line(FILE *file)
{
FILE *fp = file;
char *buffer;
int ch, i=0;
unsigned int buffer_size = BUFFER_SIZE, new_buffer_size;
assert(buffer_size > 0);
buffer = (char *) safe_malloc (buffer_size * sizeof (char));
while ((ch = getc(fp)) != EOF && ch != '\n')
{
if (buffer_size == i)
{
new_buffer_size = buffer_size * 2;
assert(new_buffer_size >= buffer_size);
buffer = (char *) safe_realloc (buffer, new_buffer_size * sizeof (char));
buffer_size = new_buffer_size;
}
buffer[i] = ch;
i++;
}
if (ch == '\n')
{
buffer[i] = '\0';
return buffer; /*finish it off with a null byte*/
}
if ((ch == EOF) && (i >= 1))
{
buffer[i] = '\0';
return buffer;
}
else
{
free (buffer);
return NULL;
}
}
Code:
bstree_t *read_index (char *file_name)
{
FILE *fp;
char *buffer, *phrase, *def_file_name;
bstree_t *index_tree = NULL;
size_t str_len, phrase_len, def_file_name_len;
fp = safe_open (file_name, "r");
while ((buffer = get_line(fp)) != NULL)
{
/*split the string at the point ";" into phrase and def_file_name then insert the value
*/
str_len = strlen (buffer);
phrase_len = strcspn (buffer, ";");
phrase = (char *) safe_malloc (phrase_len + 1 * sizeof (char));
strncpy (phrase, buffer, phrase_len);
phrase[phrase_len+1] = '\0';
def_file_name_len = str_len - phrase_len - 1;
def_file_name = (char *) safe_malloc ((def_file_name_len+1) * sizeof (char));
strcpy (def_file_name, buffer + phrase_len + 1);
def_file_name[def_file_name_len-1] = '\0';
index_tree = bstree_insert (index_tree, phrase, def_file_name);
}
return index_tree;
}
[/code]