将指针地址保存到解除引用的指针/自己的malloc函数

时间:2014-12-14 12:25:05

标签: c pointers malloc

我被困,也许是一个非常简单的问题。

在大学里,我们必须在C中创建自己的malloc函数。在解除引用的指针上保存指针Address时,我只会遇到问题。我在堆上工作,剩下足够的内存。

void *actual_pointer = sbrk(sizeof(Node));
*(char*)actual_pointer = 'O';
actual_pointer = actual_pointer+sizeof(char);
*(char*)actual_pointer = 'K';
actual_pointer = actual_pointer+sizeof(unsigned int);
*(unsigned int*)actual_pointer = size;
actual_pointer = actual_pointer+sizeof(unsigned int);
*(unsigned int*)actual_pointer = 0;
actual_pointer = actual_pointer+sizeof(unsigned int);
*actual_pointer = actual_pointer;

最后一行不起作用。我尝试了一切。是不是可以将一些指针地址存储到解除引用的指针?

typedef struct _Node_ 
{
  char checkCorruption_[2];
  unsigned int size_;
  unsigned int status_;
  char *location_;
  struct Node *next_;
  struct Node *prev_;
} Node;

这是我的双链表的结构,代表了结构。

我的想法如下: 我们需要制作一个简单的malloc函数。从main函数调用例如data[1] = malloc(100 * sizeof(int))。然后我将在mallocfunction中创建一个Node并在其中存储“checkCorruption”-Value'OK'。在它的大小之后,在我的例子中“100 * sizeof(int)”。在此之后,我将一个0用于使用或一个免费存储在其中。然后我将存储返回到data [0]的位置 - 存储与sbrk(100*sizeof(int))一起保留并从该位置开始。然后我将指针存储到下一个节点和前一节点。

我总是检查OK值,如果其他某个malloc有溢出并将其覆盖 - 那么我将退出并出错。

我的想法完全废话还是没事?

EDIT2:

当我现在使用Node而不是void时,我也可以存储我的位置指针到节点。

Node *actual_pointer = sbrk(sizeof(Node));


actual_pointer->checkCorruption_[1] = 'O';
printf("actual_pointer: %p\n", actual_pointer);
printf("actual_O: %c\n", actual_pointer->checkCorruption_[1]);
printf("actual_pointer_before: %p\n", actual_pointer);
actual_pointer = actual_pointer+sizeof(char);
printf("actual_pointer_after: %p\n", actual_pointer);

输出:

actual_pointer: 0x1ad4000
actual_O: O
actual_pointer_before: 0x1ad4000
actual_pointer_after: 0x1ad4028

但现在我遇到actual_pointer = actual_pointer+sizeof(char);的一些问题。这个命令应该将char的大小添加到actual_pointer但是它会增加40个字节的指针?我不明白这个?

先谢谢,

菲利普

1 个答案:

答案 0 :(得分:1)

无法将价值存入虚空......

尝试用

替换最后一行
*(unsigned int*)actual_pointer = (unsigned int*)actual_pointer
相关问题