i am getting an error - (Exception thrown at 0x00F06195 in Project1.exe: 0xC0000005: Access violation writing location 0x80FC8581.)
for (int i = 2; i < max; i += 2) {
arr[i] = true;
}
for (int i = 3; i < max; i += 2)
{
if (!arr[i])
{
for (int j = i * i; j < max; j += i)
{
arr[j] = true;
}
}
}
for (int i = 2; i <= max; i++)
{
if (!arr[i])
vi.push_back(i);
}
}
can anyone help
To understand the reason of the exception, you need to know the location and values of all variables involved. I would strongly suspect that the variable arr is smaller by size than the index you use, or maybe even something like null. But let's answer the question as it stands from the title. There are multiple ways to deal with this situation:
Add multiple assert statements to verify indices and sizes of array, validity of pointers, especially at suspicious places. Assertions make no harm, you can auto-exclude them from the production build.
Use CLion IDE to run your code under debuger (do not put any
breakpoints). After the fault, Clion will show you the stack trace
and values of all variables. Check the size and condition of the
arr
variable, the variables that make the index and the variables
that we possibly used to initialize arr
. It is a paid IDE but it has
a free trial, so can help you this time anyway.
Place multiple printf
statements at variable locations and check what is
printed last before the crash. After you
narrow the range of the fault happening, place more statements to pin
the misbehaving sentence precisely. Then add the printf
statement to
output everything relevant immediately before. Even if the fault
happens not the first time the execution passes the sentence, all you
need is to examine the end of the output after the crash. After you
understand, just use git to revert all changes (or save a backup copy
if you do not use the repository). This method may not look very nice
but it works.
There are also older approaches to get the stack trace, covered here.
User contributions licensed under CC BY-SA 3.0