-3

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);
}
FireTner
  • 11
  • 3
  • Pointers are not arrays. – 12345ieee Mar 11 '21 at 11:47
  • The line `cpu->dCache[3] = 5;` dereferences the uninitialised pointer `cpu->dCache` and then writes to the random address found a `5`. – alk Mar 11 '21 at 11:48
  • 1
    `CPU->dCache` is an uninitialized pointer. – Paul Hankin Mar 11 '21 at 11:48
  • You may find https://clang.llvm.org/docs/MemorySanitizer.html helpful. – Paul Hankin Mar 11 '21 at 11:51
  • [don't cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – klutt Mar 11 '21 at 11:52
  • A pointer is an index (or address) of a memory cell, if you think of memory as a 1D array of cells. If you have a pointer to a string, for example, than you have an index of the memory cell, whe the first character of the string is stored. Next characters follow. You really need to study it first a bit, so that you know exactly what you're doing and what you are asking. – Jiri Volejnik Mar 11 '21 at 12:14

1 Answers1

1

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;
}
FireTner
  • 11
  • 3