Hello everyone. I have a problem using strtok in C. I get a user input from the command line and I want to tokenize it with pipe ("|") as the delimeter and put the result in a double pointer variable. Here's my code:
Wow thanks. That's a very nice code. Cleared some confusion I had pointers. I now understand a little bit my problem. There's a little problem with your code. When I get the user input from the command line, I initialise a double pointer variable to split_str
And that, my friend, is proof that regardless of your experience or ability, stupid mistakes happen. Especially if you work with higher level language too often and then drop down to a low level language that doesn't hold your hand. ;)
I have a various header files so putting all the code would look really messy. That's why I didn't put everything here. I actually made another c source file independent of all my header files and pasted the code above. It compiles well but when I execute it, it gives me the same error I posted above. Which syntax error did you fix on my fgets()?
EDIT: It's works partially. If I type "a | b". It doesn't work. But if I type "a | b | c". It works. Weird.
I found out that the problem was actually the "free(src)" in split_str function
dst[n] = NULL;
Since the error was about an invalid pointer. I tried commenting that part and everything works. I suspect that it was trying to free a pointer that doesn't exist which kind of doesn't make sense. Not sure if i'm right. I know it's important to free buffers we don't need anymore from the memory but do we need to free(src)? Since it's a local variable, it's reach is just in the function split_str.
I suspect that it was trying to free a pointer that doesn't exist which kind of doesn't make sense.
This is a case where I don't see an immediate problem. It would probably take some debugging, but as I cannot reproduce the error, I can't help too much. It's a shame, because I'd be interested to know exactly what's causing your error.
I know it's important to free buffers we don't need anymore from the memory but do we need to free(src)?
Unless the process lives for a long time, it's not technically necessary. On modern operating systems the memory allocated dynamically will be freed when the process terminates. However, one can't determine conclusively how library functions such as split_str() might be called, so it's an excellent idea to clean up after yourself.
You can get rid of the allocation entirely (and thus the need for free()) by assuming that s is modifiable. This puts the onus on the caller to refrain from calling split_str() with something like a string literal. The reason for that is strtok() modifies the source string, and string literals are read-only: