两个双字符指针**行和** splitted_line之间存在一个奇怪的地址问题。在strcpy之后,一些char *参数消失了。
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;
}
在开头的char **行:
0:决议600 600 1:pps 5 2:尼克斯 3:风180 10 4:引力6.5
最后:
0:分辨率 1:pps 5 2:尼克斯 3:风180 10 4:万有引力
需要一些帮助!
答案 0 :(得分:1)
使用buffer = (char)malloc(...)
,您将动态分配的内存指针的值从4或8个字节(取决于您的平台)截断为1个字节。
此后的代码会产生未定义的行为。