私は自分のコードの "意味"部分を抽出しました(また、単純化するためにいくつかの行を置き換えています)。strtokの後でポインタトークンを解放したい
私は2つのダイナミックポインタを持っています.1つは現在の行(ファイルから抽出)で、もう1つは現在のトークンです。
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を使用してのようにエレガントではない、この解決策を見つける
「保存: この質問に続いて、 Free/delete strtok_r pointer before processing complete string? は私がこれを書きました変数」が正しい、それを改善するためのいくつかの方法があります おかげ
編集ということです:。??、このために私のコードを変更する(そしてそれは、ファイルのすべての行を処理します)
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;
}
あなたは私が必要ないと言いますfreetok2変数ですが、私がフリーにしようとすると(tok2);私はヒープエラー(無料無効ポインタ)を取得します。 それ以外の場合は、すでにintを使用しているため、+1をntcに入れていません(文字列のサイズをあらかじめ知っていないので、300文字未満であることがわかります)。 – roro
@roroあなたは 'free(tok2)'をする必要はありません。 'free(line)'だけが必要です。 – cnicutar
私はそのようなことを期待していましたが、どのように可能ですか? – roro