好的快速介紹。我正在做動態分配內存的功課。我們需要使用結構體和dyn來模擬CPU。人。記憶。我正在測試我的堆棧是否正常運行並且不會溢出。該堆棧應該是2 KiB,沒有溢出,但在打印數字時,很少有地址包含其他數字,我沒有放入。我只是在這裏複製它,並擺脫指令列表,寄存器等,這不是一個問題,並會使這個很長。從動態分配的內存打印時值發生變化
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
struct cpu {
struct stack* memory;
};
struct stack {
int32_t* values;
int32_t* top;
};
void stackInit(struct stack* stack)
{
stack->values = malloc(2048);
stack->top = NULL;
}
void cpuInit (struct cpu* cpu)
{
stackInit(cpu->memory); //initialize stack
}
void stackPush(struct stack* stack, int32_t value)
{
if (stack->top == NULL){
stack->top = stack->values;
*(stack->top) = value;
}
else if (stack->top + sizeof(int32_t) < stack->values + 2048){
stack->top += sizeof(int32_t);
*(stack->top) = value;
}
}
void cpuDebug(const struct cpu* cpu)
{
int32_t* auxpt = cpu->memory->top;
if (cpu->memory->top != NULL)
for (int32_t i = 0; auxpt >= cpu->memory->values; i++){
printf("Value on the addr %d\n", *auxpt);
printf("Address of auxpt: %p\n", (void *)auxpt);
auxpt -= sizeof(int32_t);
}
printf("\n");
}
int main()
{
struct cpu Cpu;
cpuInit(&Cpu);
for (int32_t i = 0; i < 550; i++){
stackPush(Cpu.memory,i);
}
cpuDebug(&Cpu);
return 0;
}
和輸出是這樣的:
Value on the addr 133
Address of auxpt: 0x562640529880
Value on the addr 10
Address of auxpt: 0x562640529870
Value on the addr 544108298
Address of auxpt: 0x562640529860
Value on the addr 2016419898
Address of auxpt: 0x562640529850
Value on the addr 1919181889
Address of auxpt: 0x562640529840
Value on the addr 128
Address of auxpt: 0x562640529830
Value on the addr 127
任何想法,爲什麼會出現這種情況? 在此先感謝
'stack-> values + 2048'返回比'stack-> values'更高的地址'2048 * 4'個字節。這遠遠超出了分配的空間。指針算術是棘手的,這就是爲什麼你更好地使用數組符號和適當的類型。 –
你正在處理棧結構中的一個指向'int32_t'的指針......所以當你添加/減去它時,它的單位是sizeof(int32_t)'字節,而不是單個字節。所以,例如。 'stack-> top + = sizeof(int32_t);'增加sizeof(int32_t)* sizeof(int32_t)'字節,而不僅僅是'sizeof(int32_t)'字節。 – Dmitri
非常感謝。我記得那件事。 – St4lker