c - 从动态分配的内存打印时值发生变化

标签 c memory dynamic printing

好的快速介绍。我正在做关于动态分配内存的作业。我们需要使用 structs 和 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

知道为什么会这样吗? 提前致谢

最佳答案

伙计,你必须在访问它们的成员(valuestop)之前分配结构堆栈。您正在访问非分配内存。

void stackInit(struct stack* stack)
{
    stack = malloc(sizeof(struct stack));
    stack->values = malloc(2048);
    stack->top = NULL;
}

按照评论中指出的技巧,更好的解决方案可能是:

void stackInit(struct stack** stack)
{
    (*stack) = (struct stack*)malloc(sizeof(struct stack));
    (*stack)->values = (int32_t*)malloc(2048);
    (*stack)->top = NULL;
}

void cpuInit(struct cpu* cpu)
{
    stackInit(&cpu->memory); //initialize stack
}

这样,调用者将在 Cpu.memory 的上下文中看到分配的内存。

关于c - 从动态分配的内存打印时值发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43143744/

相关文章:

C 程序用文件中的替换值生成字符串

c++ - 动态堆栈内存重新分配

sql - 使用映射表动态更改列名

C 链表段错误(核心转储)错误

c - 互斥锁 vs 忙等待 tcp io

无法通过 dev_queue_xmit() 发送数据包

c - 在 C 中返回一个字符串

c - 写入视频内存(0xB8000)和 volatile 指针

iphone sqlite3对象分配内存增加但没有泄漏

C - 'struct' 元素的动态数组