【发布时间】:2014-12-07 14:53:57
【问题描述】:
以下是简单的malloc 实现的代码。链表由用于内存管理的头尾指针启动。现在在函数中,当列表未初始化时,只实现了一个调用,其中初始化了列表的头部。一旦我将底层指针返回到main,程序就会给出segmentation fault。另一方面,下面的test 函数除了对链表的复杂处理外,具有几乎相同的参数,可以正确计算并显示结果。谁能告诉我这里缺少什么?
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <sys/types.h>
typedef struct Items{
size_t size_of_object;
size_t free;
} Items;
typedef struct Node{
void *ptr;
void *next;
Items Item;
}Node ;
typedef struct LinkedList{
Node *head;
Node *tail;
} LinkedList;
LinkedList memory_list;
void *salmalloc(size_t size_of_object) {
if (memory_list.head == NULL) {
memory_list.head = sbrk(sizeof(Node));
memory_list.head->ptr = sbrk(size_of_object);
memory_list.head->Item.size_of_object = size_of_object;
memory_list.tail = NULL;
memory_list.head->next = NULL;
memory_list.head->Item.free = 1;
return memory_list.head->ptr;
}
}
void *test(size_t size) {
void *p = sbrk(size);
return p;
}
void main(){
char *p = NULL;
char a = 'B';
p = salmalloc(sizeof(char));
*p = a;
printf("%c\n", *p);
}
【问题讨论】:
-
if (memory_list.head == NULL)这个在哪里初始化为NULL?为什么要显示有效的代码?为什么不显示不起作用的代码? -
@PaulMcKenzie,
salmalloc功能不起作用。 -
On the other hand, the following test function with almost the same parameters except for the complicated handling of linked list computes correctly and displays the result.那么你发布的功能是否有效? -
void test有效,但salmalloc无效。
标签: c++ c linux memory memory-management