Loading text lines cause memory corruption
I'm trying to load a simple file with text lines on it and store on a proper structure. The code i'm working on is:
Code:
BOOL loadtextfile(char* filename, TEXTBUFFER* t)
{
FILE* fp;
char line[MAX_LINE];
int i = 0;
fp = fopen(filename, "r");
if (!fp)
return FALSE;
fgets(line, MAX_LINE, fp);
while (!feof(fp))
{
t->linebuffer[i] = (char*)xmalloc(MAX_LINE);
line[strlen(line)-1] = '\0'; /* quit CR */
strncpy(t->linebuffer[i], line, strlen(line) );
i++;
fgets(line, MAX_LINE, fp);
}
t->numTextLines = i;
fclose(fp);
return TRUE;
}
A TEXTBUFFER is a struct defined as:
Code:
typedef struct
{
int numTextLines; /* numero de lineas de texto fuente*/
char* linebuffer[];
} TEXTBUFFER;
I don't know how reading lines (from a proper formatted lines) trash other memory areas... :(
Re: Loading text lines cause memory corruption
You need to allocate the array size (linebuffer) as well. You can't do that without knowing the number of read in lines.
Maybe you should store the lines in a linked-list instead.
Code:
typedef struct
{
int numTextLines; /* numero de lineas de texto fuente*/
LINKEDLIST *head;
LINKEDLIST *tail;
} TEXTBUFFER;
typedef struct _LINKEDLIST
{
char *str;
struct _LINKEDLIST *next;
} LINKEDLIST;
Re: Loading text lines cause memory corruption
As j0nas said, you might be writing past your "t" array.
Also, in this code:
Quote:
Originally Posted by indiocolifa
Code:
line[strlen(line)-1] = '\0'; /* quit CR */
if your line is empty, you will write '\0' right before it.
P.S. Does the line read with fgets() contain CR at the end?
Re: Loading text lines cause memory corruption
Yes, a linked list seems suitable for this. If it is opened in text mode, it will only have an LF. If it is in binary mode, it will have a CRLF. I would also say
Code:
while(fgets(line, MAX_LINE, fp))
Also, if you are just going to be doing
Code:
t->linebuffer[i] = (char*)xmalloc(MAX_LINE);
I don't see why you're dynamically allcoating it. I'd allocate enough memory for strlen(line) + 1
>> if your line is empty, you will write '\0' right before it.
I think if the line is empty, it will look like "\n\0".