Reputation: 12085
I'm trying to separate a string based on some delimeter in a kernel module.
I'm trying to use the strsep()
function, but when I try to use it my kernel crashes.
Can someone identify the bug in the code below?
char *test = "test1:test2:test3";
char *token = test;
char *end = test;
while (token != NULL) {
strsep(&end, ":");
token = end;
}
kfree(test);
Upvotes: 2
Views: 2935
Reputation: 53006
You are passing a string literal and strsep()
modifies it, it's undefined behavior, try like this
char test[] = "A:B:C:D";
you should not free(test)
, not the one in this suggestion, and also not the one in your code.
You are free()
ing test
, which is worst, you should learn about pointers and dynamic memory before attempting to write c code, specially if it will be a kernel module.
If you want, the compiler may warn you about that, but you should help the compiler by declaring any pointer that will point to a string literal, as const
, for example in your case
const char *test = "Whatever";
then the compiler will say something like the first parameter to strsep()
discards const
qualifier, which would probably not prevent it from compiling but will let you see that you did something wrong.
Upvotes: 3