简体   繁体   English

Linux内核空间中的动态内存分配

[英]Dynamic Memory Allocation in Linux Kernel Space

I'm having trouble allocating memory is Linux Kernel space. 我在分配内存时遇到麻烦是Linux内核空间。 I've created a linked list using the two structs below: 我使用下面的两个结构创建了一个链表:

struct Node{
    char *ptr;
    struct Node *next;
};

struct List{
    struct Node *head;
    struct Node *tail;
};

Now when I try and allocate a list struct [Edited to reflect proper code]: 现在,当我尝试分配一个列表结构[编辑以反映正确的代码]时:

struct List *ll = kmalloc(sizeof(struct List), GFP_KERNEL)

I get: 我明白了:

error: Initializer element is not constant

What am I doing wrong here? 我在这做错了什么? I want to be add pointers to Nodes in my List struct so would I add them by: 我想在我的List结构中添加指向节点的指针,所以我会通过以下方式添加它们:

struct Node n* = kmalloc(sizeof(Node));
n -> ptr = "Blah";
n -> next = NULL;
ll -> head = n;

Not

struct List ll*;

but

struct List *ll;

You got this right in your type definitions, but wrong in both lines with kmalloc . 你在类型定义中得到了这个权利,但在使用kmalloc两行中都是错误的。

The ERROR is not related to kernel programming, it is related to c programming. ERROR与内核编程无关,它与c编程有关。

error: Initializer element is not constant

Code: 码:

 struct List{
    struct Node *head;
    struct Node *tail;
};
struct List *ll = kmalloc(sizeof(struct List), GFP_KERNEL)

The structure object (by default) has static storage class. 结构对象(默认情况下)具有静态存储类。 Initialization of Objects with Static Storage Duration must be with constant expression. 具有静态存储持续时间的对象的初始化必须具有常量表达式。 Try allocating memory inside main() function. 尝试在main()函数中分配内存。

Objects with static duration are declared either outside functions, or inside them with the keyword extern or static as part of the declaration. 具有静态持续时间的对象在外部函数中声明,或在其中使用关键字extern或static作为声明的一部分声明。 These can only be initialized at compile time. 这些只能在编译时初始化。 ie, with constant expression 即,持续表达

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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