简体   繁体   中英

Linux kernel: why does this call to kstrtol crash?

I am learning kernel programming and have a simple call to kstrtol I am using to convert a string to a number. However, everytime I compile this module and use insmod to place it in the kernel, I get "BUG: unable to handle kernel paging request at f862b026" and then a register and stack dump.

I'm following the definition from here: https://www.kernel.org/doc/htmldocs/kernel-api/API-kstrtol.html . It seems like a really simple call. What am I doing wrong here?

#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); 

You cannot modify string literals. Copy it into an array firstly.

edit: use this instead

char mystr[] = "abdc";

edit2: the underlying reason for this is, that a char pointer to a string literal points to a data segment, usually readonly. If you alter this memory you might get a crash. When you create an array of chars instead, the string literal gets copied into the array on the stack, where you safely can modify it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM