Search code examples
cstringpointersmemory-managementfree

Can I/ Should I free pointer returned by strtok


So I am dynamically creating an array of strings. I am then assigning each element in that array a pointer returned by calling strtok. At the end of my process when I need to redo everything I have been trying to free the pointers in the elements of said array, but I keep getting an error stating

*** glibc detected *** ./prgm: munmap_chunk(): invalid pointer: 0x00007fff600d98

Also, would it make sense to free inputStr at the end of the loop?

Where is my logical "not really logical at all" thinking wrong.. e.g code

   char** argvNew = (char**)calloc(33,sizeof(char*));
   char inputStr[128];  
   do{    
        scanf("%127[^\n]%*c", inputStr);
        token = strtok(inputStr, delim);

        /* Add tokens to array*/
        varNum= 0;
        for(i = 0; token != NULL; i++){
            varNum++;
            argvNew[i] = token;
            token = strtok(NULL, delim);
        }
        argvNew[i] = NULL;

       //Free argvNew 
        for(i = 0; i < varNum;i++){
            printf("Deleting %i, %s\n",i,argvNew[i]);
            free(argvNew[i]);
        }
  while(1);

Solution

  • No, you should not free it. It's returning a pointer to a character in inputStr (or NULL when it reaches the end). It's not allocating any new memory, so there's nothing to free.

    If inputStr is dynamically allocated, you should free it when you're done with it.