Search code examples
cpointersmemorystructmemcpy

C memcpy crashing at run time


i have this issue. Whenever i try to call StorageStore it crashes on run time. I have no idea how to fix it. I have tried googling but iam kinda inexperienced about pointers. Thanks in advance.

Edit: i compile with gcc -Ofast

uint8_t Storage[256];

typedef struct _QCPU {
    uint8_t pc; // 1
    uint8_t *regs; // 7
    uint8_t *dCache; // 8 (32)
    uint8_t *iCache; // 8 (32)
    uint8_t **port_table; // 8 (8)
    void *str_load; // 8 (1)
    void *str_store; // 8 (1)
    struct Flags flags;
} QCPU;

void StorageStore(QCPU *CPU, uint8_t Addr)
{
    memcpy(Storage+(Addr & 0xE0), CPU->dCache, 32);
}

QCPU* init()
{
    return (QCPU*) malloc(sizeof(QCPU)); // Return Allocated Pointer To QCPU
}

int main()
{
    QCPU *cpu = init();
    cpu->dCache[3] = 5;
    StorageStore(cpu, 5);
    free(cpu);
}

Solution

  • After googling about what uninitialised pointer is i realized my issue

    thank you alk, Paul Hankin and Jiri Volejnik for your answers

    i added these line to fix it

    QCPU* init()
    {
        QCPU* r = malloc(sizeof(QCPU)); // Allocated Pointer To QCPU
        r->dCache = malloc(32);
        r->iCache = malloc(32);
        r->port_table = malloc(8);
        return r;
    }