I am getting this error
Exception thrown at 0x0FC04AFF (vcruntime140d.dll) in Ergasia.exe: 0xC0000005: Access violation writing location 0x00000020.
If there is a handler for this exception, the program may be safely continued.
Which takes me to this part of my code :
for (unsigned int i = 0; i < width*height * 3; i = i + 3) {
file.read((char *)cR, 1);
file.read((char *)cG, 1);
file.read((char *)cB, 1);
buffer[i] = cR / 255.0f;
buffer[i + 1] = cG / 255.0f;
buffer[i + 2] = cB / 255.0f;
}
I tried using try/catch and some other if checks but neither worked. Anyone knows what's causing it?
What's causing it is that you are trying to write to memory at location 0x20, but that is impossible, because there is never any writable memory located at such a low memory location. You could have figured this out rather easily by reading the error message:
Access violation writing location 0x00000020
The obvious next question is where you're getting a pointer to memory at the address 0x20, since that is obviously not a valid address. Your code is somewhat incomplete, using variables whose definitions we cannot see, but it looks to me like you are casting character values to char*
, which is almost certainly incorrect. Presumably, cR
, cG
, and cB
is supposed to be the intensity of the red, green, and blue color channels for an RGB bitmap. They are not pointers to memory, so you should not be casting them to char*
as if they were.
I'm assuming that file.read
is a function that reads a color value from a file, and writes it into the memory location pointed to by its first parameter. If that's true, then you should be passing the address of the variable to the function, rather than casting the value to a pointer. The &
(address-of) operator is used in C++ to retrieve a pointer to a variable:
file.read(&cR, 1);
file.read(&cG, 1);
file.read(&cB, 1);
As others have rightfully pointed out in the comments, you should not be catching Access Violation errors. And, in general, you should make sure that an exception is not being caused by a bug in your program before trying to catch and ignore it.