There is a strange address problem between the two double char pointers **lines and **splitted_line. After the strcpy some char* arguments disappear.
Error readFile(FILE *file, ConfigValues *values)
{
int filesize;
char *buffer;
size_t readchars;
char **lines = malloc(sizeof(char*));
char **splitted_line = malloc(sizeof(char*));
char *buffer_line;
char *buffer_token;
int counter_lines = 0;
int counter = 0; //TODO reneme
int counter_argument = 0;
int printf_counter = 0; //TODO to be deleten
fseek(file, 0, SEEK_END);
filesize = ftell(file);
rewind(file);
buffer = (char*) malloc(sizeof(char) * filesize);
if (buffer == NULL)
{
printf(ERROR_OUT_OF_MEMORY);
return OUT_OF_MEMORY;
}
readchars = fread(buffer, sizeof(char), filesize, file);
if (readchars != filesize)
{
printf("Reading error\n");
return OTHER;
}
printf("%s\n", buffer);
//unfortunately you cant nest strtok, cuz of the NULL-param in the while!
buffer_line = strtok(buffer, "\n");
while (buffer_line != NULL)
{
lines = realloc(lines, (counter_lines + 1) * sizeof(*lines));
lines[counter_lines] = (char*) realloc(lines[counter_lines],
strlen(buffer_line) * sizeof(char*));
printf("Stelle lines: %p, %p\n", lines, lines[counter_lines]);
strcpy(lines[counter_lines], buffer_line);
counter_lines++;
buffer_line = strtok(NULL, "\n");
}
printf("counterlines: %d\n", counter_lines);
while (printf_counter < counter_lines)
{
printf("%d: %s\n", printf_counter, lines[printf_counter]);
printf_counter++;
}
//TODO repair from down here
while (counter < counter_lines)
{
printf("%d:: %s\n", counter, lines[counter]);
buffer_token = strtok(lines[counter], " ");
printf("Erstes argument der zeile: %s\n", lines[counter++]);
while (buffer_token != NULL)
{
splitted_line = realloc(splitted_line,
(counter_argument + 1) * sizeof(*splitted_line));
printf("Stelle splitted lines: lines: %p, %p\n", splitted_line, lines[counter]);
splitted_line[counter_argument] = (char*) realloc
(splitted_line[counter_argument],
strlen(buffer_token) * sizeof(char*));
printf("%d, counter_argument: %d\n", strlen(buffer_token), counter_argument);
strcpy(splitted_line[counter_argument], buffer_token); //the evil line!!!
printf("gespeichert: %s\n", splitted_line[counter_argument]);
counter_argument++;
buffer_token = strtok(NULL, " \n");
printf("test2: %s\n", buffer_token);
}
printf("-----------\n");
counter_argument = 0;
counter++;
}
return SUCCESS;
}
At the begin the char** lines:
0: resolution 600 600 1: pps 5 2: nix 3: wind 180 10 4: gravitation 6.5
At the end:
0: resolution 1: pps 5 2: nix 3: wind 180 10 4: gravitation
Need some help!
With buffer = (char)malloc(...)
, you are truncating the value of the dynamically allocated memory pointer from 4 or 8 bytes (depending on your platform) to 1 byte.
The code thereafter yields undefined behavior.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.