In my program, I receive text from a .txt file. Here is an example of a line of text:
12X15 de3 ds4 dn9 g2,7 m5,9 m3,1 h2,2
I am trying to use strtok() to break up each chunk of text; I will then put each chunk as an element in an array. So an array of strings.
Here is my code so far:
void parseFile(char ** argv) {
FILE *textFile;
char *string;
char **lineToken;
int i;
textFile = fopen(argv[1], "r");
lineToken = malloc(sizeof(1));
string = malloc(sizeof(MAX_CHAR));
while(fgets(string, MAX_CHAR, textFile) != NULL) { /* Get first line of text */
lineToken[0] = strtok(string, " "); /* Put first element in lineToken[0] */
for(i = 1; i; i++) {
/* Realloc because total number of elements is unknown */
lineToken = realloc(lineToken, i + 1);
/* Put new strtok'd string into lineToken[i] */
lineToken[i] = strtok(NULL, " ");
}
for(i = 0; i; i++) {
move(i, 0);
printw("%s", lineToken[i]);
refresh();
}
}
free(lineToken);
free(string);
} /* End of function */
But I keep getting this realloc error:
*** glibc detected *** ./bin/a3RunMe: realloc(): invalid next size: 0x01f2a270 ***
Aborted
This is the most likely problem:
lineToken = malloc(sizeof(1));
Here you allocate the size of an integer literal, but lineToken
needs at least sizeof(*lineToken)
(or sizeof(char *)
) bytes. The size of an integer and the size of a pointer may not be the same, especially on a 64-bit platform (where int
is four bytes and pointers are eight bytes).
So when you do
lineToken[0] = strtok(string, " ")
you write beyond what's allocated (buffer overflow) and overwrite data put there by the allocator.
There's also a problem with the realloc
call which will allocate i + 1
bytes. So even when you're on a 32-bit platform (where the size of int
just happens to be the same as the size of a pointer) you will reallocate the pointer from being four bytes to two bytes in the first iteration of the loop.
You also have other problems, like these loops:
for(i = 1; i; i++)
Remember that in C all non-zero values are true, and when will i
ever be zero in that loop?