我卡住了,也许是一个非常简单的问题。
在大学里,我们必须在 C 中创建自己的 malloc 函数。我只有在将指针地址保存在取消引用的指针上时才会遇到问题。我在堆上工作,还有足够的剩余内存。
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 函数。例如从主函数 data[1] = malloc(100 * sizeof(int))
被调用。然后我将在 mallocfunction 中创建一个节点并在其中存储“checkCorruption”-Value“OK”。在它之后是大小,在我的例子中是“100 * sizeof(int)”。在此之后,我在其中存储一个 0 用于使用或 1 用于免费。然后我将存储返回到 data[0] 的位置 - 存储通过 sbrk(100*sizeof(int))
保留并从该位置开始。然后我将指针存储到下一个节点和前一个节点。
如果其他一些 malloc 发生溢出并覆盖它,我总是会检查 OK 值 - 然后我会以错误退出。
我的想法是一派胡言还是没问题?
编辑2:
当我现在使用 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 个字节?我不明白这个?
提前致谢
菲利普
最佳答案
不可能将值存储到空...
尝试用
替换最后一行*(unsigned int*)actual_pointer = (unsigned int*)actual_pointer
关于c - 将指针地址保存到取消引用的指针/自己的 malloc 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469266/