Want to free pointer token after strtok

I extracted part of the "value" of my code (and also replaced some string to simplify it).

I have 2 dynamic pointers, one for the current line (extracted from the file) and the second for the current token. After this question, delete / delete the strtok_r pointer before processing the full line? I wrote this:

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; } 

But in the end, I'm not sure what is right or not, and I find this solution not very elegant (due to the use of 2 "save variables".

It is right? Is there any way to improve it? Thanks

Edit: changed my code for this (and it will process all lines of the file)

 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; } 
+4
source share
2 answers

In fact, you are not using the memory marked freetok2 , you do not need anything malloc , so you do not need the freetok2 variable.

Saying free(line) or free(freeline) is the same in your code so you don't need freeline at all.

Another problem is the following: malloc(n*sizeof(*line)); . You could also say: malloc(n); , because sizeof(char) always 1. But it would be best:

 line = malloc(strlen(file_reading) + 1); strcpy(line, file_reading); 
+5
source

The code should be changed as follows:

 int main(void) { int n = 455; char *tok2; char *line; line = malloc(n*sizeof(*line)); /* 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(line); return 0; } 
+2
source

Source: https://habr.com/ru/post/1395792/


All Articles