You don't need to allocate memory when using strtok()
There is no problem in freeing filename as it is correctly allocated by malloc(), however there are many other problems and memory leaks.
Basically you first allocate memory for str_ptr:
strk_ptr = malloc(sizeof(filename));
Here malloc() return a pointer which is stored in strk_ptr.
And then you call strtok() which also return a pointer, inside filename:
strk_ptr = strtok(filename,".");
So you lost the original pointer returned by malloc() and now strk_ptr points somewhere in filename. When you call free(str_ptr)
you are freeing a memory inside filename. The subsequent call to free(filename)
report the error. The solution is simply that don't need to allocate memory for strk_ptr.
I wrote a working minimal code to show you how to correctly use strtok. Please remember that, when asking a question, posting a minimal working code is alway better.
int main(int argc, char **argv) {
char *strk_ptr;
char *filename = malloc(strlen(argv[0]) + 1);
strcpy(filename, argv[0]);
printf("filename = %s, size = %zu\n", filename, sizeof(filename));
// Do not malloc this
//strk_ptr = malloc(strlen(filename) + 1);
strk_ptr = strtok(filename,".");//
printf("%s\n", strk_ptr);
while( (strk_ptr = strtok(NULL,".")) )
{
printf("%s\n", strk_ptr);
}
free(filename);
return 0;
}
First of all argv is a char** so if you want to copy the content of the first argument passed as input you have to use argv[0], which is always the executable file name.
then, sizeof(filename)
returns the size of the pointer not the size of the content as filename is not an array. you have to use strlen(filename) + 1
.
strtok return a pointer inside the object (filename) which is already allocated so you don't need to allocate memory for strk_ptr.
When using strtok in a loop consider to take the following approach:
for (strk_ptr = strtok(filename, "."); strk_ptr; strk_ptr = strtok(NULL, "."))
{
printf("%s\n", strk_ptr);
}