So I decided to write a function to take a file, and put each line into its own element of an array, for example...
file.txt
Code:
char **data;
data[0] = X
data[1] = YHOO
data[2] = FCX
Here is what I am doing, but I believe I am just doing some dirty things to memory, but I can't spot it.
main.c
Code:
#include <stdio.h>
#include "strlib.h"
int main (void)
{
struct strlib_gl fileinfo;
int i, j;
fileinfo.filename = "data.dat";
fileinfo.count = 0;
getlines(&fileinfo);
for (i = 0; i < fileinfo.count+1; i++)
{
for (j = 0; j < strlen(fileinfo.data[i]); j++)
printf("%c", fileinfo.data[i][j]);
printf("\n");
free(fileinfo.data[i]);
}
free(fileinfo.data);
return 0;
}
strlib.c
Code:
#include "strlib.h"
void getlines(struct strlib_gl *info)
{
FILE *fp;
int count = 0;
char *temp;
fp = fopen(info->filename, "r");
info->data = malloc((count+1) * sizeof(char *));
info->data[count] = malloc(4 * sizeof(char));
temp = fgets(info->data[count], 100, fp);
while (temp != NULL)
{
info->data[count] = temp;
count++;
info->data = realloc(info->data, (count+1) * sizeof(char *));
info->data[count] = malloc(4 * sizeof(char));
temp = fgets(info->data[count], 100, fp);
}
fclose(fp);
info->count = count;
}
struct strlib_gl
Code:
struct strlib_gl
{
char *filename;
char **data;
int count;
};
You guys see anything alarming right off the bat? Thanks for any help!
EDIT: I made one stupid error, fixed, but valgrind is still telling me some stuff
Code:
==20207== Invalid write of size 1
==20207== at 0x4026944: memcpy (mc_replace_strmem.c:402)
==20207== by 0x4097AB2: _IO_getline_info (in /lib/tls/i686/cmov/libc-2.8.90.so)
==20207== by 0x40979A0: _IO_getline (in /lib/tls/i686/cmov/libc-2.8.90.so)
==20207== by 0x4096889: fgets (in /lib/tls/i686/cmov/libc-2.8.90.so)
==20207== by 0x804872C: getlines (strlib.c:22)
==20207== by 0x804857E: main (main.c:13)
==20207== Address 0x4195264 is 0 bytes after a block of size 4 alloc'd
==20207== at 0x4025D2E: malloc (vg_replace_malloc.c:207)
==20207== by 0x8048702: getlines (strlib.c:20)
==20207== by 0x804857E: main (main.c:13)
==20207== Invalid write of size 1
==20207== at 0x40968C5: fgets (in /lib/tls/i686/cmov/libc-2.8.90.so)
==20207== by 0x804872C: getlines (strlib.c:22)
==20207== by 0x804857E: main (main.c:13)
==20207== Address 0x4195265 is 1 bytes after a block of size 4 alloc'd
==20207== at 0x4025D2E: malloc (vg_replace_malloc.c:207)
==20207== by 0x8048702: getlines (strlib.c:20)
==20207== by 0x804857E: main (main.c:13)
==20207== Invalid read of size 1
==20207== at 0x80485A5: main (main.c:18)
==20207== Address 0x4195264 is 0 bytes after a block of size 4 alloc'd
==20207== at 0x4025D2E: malloc (vg_replace_malloc.c:207)
==20207== by 0x8048702: getlines (strlib.c:20)
==20207== by 0x804857E: main (main.c:13)
==20358== Conditional jump or move depends on uninitialised value(s)
==20358== at 0x402643B: strlen (mc_replace_strmem.c:242)
==20358== by 0x80485CF: main (main.c:17)