cat text.txt
>the table stands at the window
cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i;
// char **testarr = (char**)malloc(sizeof(char*));
char *dl = ", \t\n";
char *word;
FILE *file;
file = fopen("text.txt", "r");
fseek(file, 0l, SEEK_END);
long size = ftell(file);
char *buf = (char*)malloc(size * sizeof(char));
fseek(file, 0l, SEEK_SET);
fread(buf, sizeof(char), size, file);
fclose(file);
char **testarr = (char**)malloc(size * sizeof(char*));
word = strtok(buf, dl);
for(i=0; word != NULL; i++) {
testarr = (char*)malloc(strlen(word));
strcpy(testarr, word);
word = strtok(NULL, dl);
}
free(buf);
for(int j = 0; j < i; j++) {
printf("%s\n", testarr[j]);
free(testarr[j]);
}
free(testarr);
}
./test
the
table
stands
at
the
window
--- Post updated at 10:46 ---
fixed the code, commented out the wrong line
--- Post updated at 11:41 ---
Something I am confused, I can not properly allocate memory for addresses in a dynamic array
--- Post updated at 12:34 ---
I fixed in a dynamic array.
But in the strtok function, the valgrind shows one error
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i;
char *dl = ", \t\n";
char *word;
FILE *file;
file = fopen("text.txt", "r");
fseek(file, 0l, SEEK_END);
long size = ftell(file);
char *buf = (char*)malloc(size * sizeof(char) + 1);
fseek(file, 0l, SEEK_SET);
fread(buf, sizeof(char), size, file);
fclose(file);
char **testarr = (char**)malloc(sizeof(char*));
word = strtok(buf, dl);
for(i=0; word != NULL; i++) {
testarr = (char**)realloc(testarr, sizeof(char*) + sizeof(char*) * i);
testarr = (char*)malloc(strlen(word) + 1);
strcpy(testarr, word);
word = strtok(NULL, dl);
}
free(buf);
for(int j = 0; j < i; j++) {
printf("%s\n", testarr[j]);
free(testarr[j]);
}
free(testarr);
}
--- Post updated at 13:16 ---
Collected the program with debug information and Valgrind calmed down
--- Post updated at 13:27 ---
Add words to the file
cat text.txt
the table stands at the window
and the picture hang on the wall
Run without recompiling
./test
the
table
stands
at
the
window
and
pucture
hung
on
the
wall