Hi!
when I try to run this code:

    struct Cand{
    // 0   -> not a cand
    // 0.5 -> preCand
    // 1   -> cand
    float status;
    // Row position
    int PosX;
    // Col position
    int PosY;
    /*
    *
    and many other things
    *
    */
    };
   int  rows = 1024;
   int cols = 1024;

int main(int argc, char** argv)
{
    // allocate memory for possible cand
    Cand* ptrCand =  (Cand*)malloc(sizeof(Cand)*rows*cols);

    ptrCand[16*1024+16].status = 0.5; /* exception happens here*/

}

I getthis exception:
Unhandled exception at 0x00e358e3 in t.exe: 0xC0000005: Access violation writing location 0x02028080.
any help why this happens?

Edited 4 Years Ago by salah_saleh

First step: check to see if malloc() failed before dereferencing ptrCand:

Cand* ptrCand =  (Cand*)malloc(sizeof(Cand)*rows*cols);

if (!ptrCand)
{
    cout << "malloc() failed!" << endl;
}
else
{
    ptrCand[16*1024+16].status = 0.5; /* exception happens here*/
}

if (!ptrCand){ cout << "malloc() failed!" << endl;}else{ ptrCand[161024+16].status = 0.5; / exception happens here*/}

yeah it prints malloc failed!
so what can be the reason of this?

Most likely 1,048,576 items the size of Cand is too much memory for malloc() to find and allocate in a single contiguous block. You might be able to call perror() for a more useful error message, but I'm willing to bet even if you do get a message, it'll be along the lines of what I just said.

Try allocating fewer items.

This question has already been answered. Start a new discussion instead.