Linux内核:为什么这个电话转给kstrtol崩溃? [英] Linux kernel: why does this call to kstrtol crash?

查看:1126
本文介绍了Linux内核:为什么这个电话转给kstrtol崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习内核编程,有一个简单的调用kstrtol我使用的字符串转换为数字。然而,每次我编译这个模块,并使用insmod的将其放置在内核中,我得到错误:无法处理在f862b026内核寻呼请求,然后一个寄存器堆栈转储

我在下面从这里的定义是:的https:/ /www.kernel.org/doc/htmldocs/kernel-api/API-kstrtol.html 。这似乎是一个很简单的电话。我在做什么错在这里?

 的#include<的Linux / kernel.h>静态INT __init转换(无效)
{
    长myLong;
    字符*为mynumber =342;
    mynumber的[2] ='\\ 0'; //覆盖了'2',只是让我知道肯定我有一个终止'\\ 0'    如果(kstrtol(mynumber的,10,&安培; myLong)== 0)
    {
        printk的(我们有许多\\ n!);
    }
返回0;
}静态无效__exit convert_exit(无效)
{
    printk的(模块卸载\\ n);
}宏module_init(转换);
宏module_exit(convert_exit);


解决方案

您不能修改字符串常量。将其复制到一个数组首先

编辑:用这个来代替

 字符myStr的[] =ABDC;

EDIT2:
这种情况的根本原因是,一个char指针字符串指向一个数据段,通常只读。如果改变这种记忆你可能会崩溃。
当您创建字符数组代替,字符串文字被复制到堆栈中,在那里你可以安全地修改它的数组。

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.

这篇关于Linux内核:为什么这个电话转给kstrtol崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆