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?

Recommended Answers

All 4 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.