0

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 by salah_saleh

2
Contributors
4
Replies
9
Views
5 Years
Discussion Span
Last Post by salah_saleh
0

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*/
}
0

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?

1

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.