【发布时间】:2012-02-10 15:27:19
【问题描述】:
我已经提取了我的代码的“意义”部分(并替换了一些行来简化它)。
我有 2 个动态指针,一个用于当前行(从文件中提取),另一个用于当前标记。 在这个问题之后,Free/delete strtok_r pointer before processing complete string? 我写了这个:
int main(void) {
int n = 455;
char *tok2, *freetok2;
char *line, *freeline;
line = freeline = malloc(n*sizeof(*line));
tok2 = freetok2 = malloc(n*sizeof(*tok2));
/* content of the file) */
const char* file_reading = "coucou/gniagnia/puet/";
/* reading from the file */
strcpy(line, file_reading);
strtok(line, "/");
/* get the second token of the line */
tok2 = strtok(NULL, "/");
fprintf(stdout, "%s \n", tok2); // print gniagnia
fprintf(stdout, "%s \n", line); // print coucou
/* free error */
//free(tok2);
/* worked, but maybe don't free "everything ?" */
//free(line);
free(freetok2);
free(freeline);
return 0;
}
但最后,我不确定什么是正确的,我发现这个解决方案不是那么优雅(因为使用了 2 个“保存变量”。
正确吗?有什么方法可以改善吗? 谢谢
编辑:为此更改了我的代码,(它将处理文件的所有行)
include <unistd.h>
include <stdlib.h>
int main(void) {
char *tok2;
char *line;
/* content of the file) */
const char* file_reading = "coucou/gniagnia/puet/";
const char* file_reading2 = "blabla/dadada/";
/* reading from the file */
line = strdup(file_reading);
strtok(line, "/");
/* get the second token of the line */
tok2 = strtok(NULL, "/");
printf("%s \n", tok2);
printf("%s \n", line);
/* reading from the file */
line = strdup(file_reading2);
strtok(line, "/");
/* get the second token of the line */
tok2 = strtok(NULL, "/");
printf("%s \n", tok2);
printf("%s \n", line);
free(line);
return 0;
}
【问题讨论】: