c - Linux内核: why does this call to kstrtol crash?

标签 c linux linux-kernel

我正在学习内核编程,并且对 kstrtol 进行了简单的调用,我用它来将字符串转换为数字。然而,每次我编译这个模块并使用 insmod 将其放入内核时,我都会得到“BUG:无法处理 f862b026 处的内核分页请求”,然后是寄存器和堆栈转储。

我遵循这里的定义:https://www.kernel.org/doc/htmldocs/kernel-api/API-kstrtol.html 。这似乎是一个非常简单的调用。我在这里做错了什么?

#include <linux/kernel.h>

static int __init convert(void)
{
    long myLong;
    char *myNumber = "342";
    myNumber[2] = '\0'; //Overwriting the '2', just so I know for sure I have a terminating '\0'

    if (kstrtol(myNumber, 10, &myLong) == 0)
    {
        printk("We have a number!\n");
    }
return 0;
}

static void __exit convert_exit(void)
{
    printk("Module unloaded\n");
}

module_init(convert);
module_exit(convert_exit); 

最佳答案

您无法修改字符串文字。首先将其复制到数组中。

编辑:改用它

char mystr[] = "abdc";

编辑2: 其根本原因是,指向字符串文字的 char 指针指向数据段,通常是只读的。如果你改变这个内存,你可能会崩溃。 相反,当您创建字符数组时,字符串文字会被复制到堆栈上的数组中,您可以在其中安全地修改它。

关于c - Linux内核: why does this call to kstrtol crash?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19186103/

相关文章:

linux - 在 Windows 7 机器上使用 git

linux - 使用-O0 编译linux kernel (4.4) bpf samples 导致错误

x86 的 Linux 系统调用调用

C 程序不断返回 1

java - 启动时运行脚本

c - 快速连续文件写入的危险是什么?

linux - 详细收听文件更改

c++ - kernel.kallsyms 在 C++ 应用程序运行中的作用

c - 不使用 strlen 和使用 C 中的函数来查找字符串长度

c - 这个函数中未初始化的值在哪里?