[英]Using strsep in kernel space to separate a string
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. 我正在尝试使用
strsep()
函数,但是当我尝试使用它时,内核崩溃。
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);
You are passing a string literal and strsep()
modifies it, it's undefined behavior, try like this 您正在传递字符串文字,并且
strsep()
修改,这是未定义的行为,请尝试像这样
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. 您不应该
free(test)
,而不是这个建议中的一个,也不应该在您的代码中一个。
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. 您正在进行
test
free()
test
,这是最糟糕的情况,最糟糕的是,您应该在尝试编写c代码之前(尤其是它将成为内核模块的情况下)了解指针和动态内存。
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
)来帮助编译器,例如在您的情况下
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. 然后编译器会说类似
strsep()
的第一个参数的内容 ,它会丢弃const
限定符 ,这可能不会阻止它进行编译,但会让您看到做错了什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.