debug assertion error

hello
I prepared a following code in visual studio 2017 and when I want to run it in debug state then an error will occurred about debug assertion and I think there is a bug in my code(when I run it with release state I dont have this error and it will run successfully).
Last edited on
in this line: for (i = 1, x = 0; i < pow(2, r); i = pow(2, x)) I have a warning that "=" the conversion among double to int may loss a data!!

pow return a double. Converting a double to an int loses the decimal part so that is what Visual Studio is trying to warn you about. If you're fine with this you could add an explicit cast (i = static_cast<int>(pow(2, x))) but due the imprecise nature of floating-point numbers you might not get the correct answer. A more robust solution would be to compute the power of 2 using integers. For positive values it can be done very easily using the left-shift operator.

1
2
3
4
5
6
7
8
#include <cassert>

// Computes the nth power of two.
int ipow2(int n)
{
	assert(n >= 0);
	return (1 << n);
}
Last edited on
the warning isnt critical, its telling you that pow returns a double, which is then compared against an integer, which may not be correct. Make sure your math is correct, cast it to clear the warning, and move on. If its a small int power of 2, consider just making a lookuptable...

const int pow2[] = {1,2,4,8,16,32,64,128,... etc};
pow2[x] is your value. its much faster, and will clear the warning, and will give correct values (no double roundoffs). This clearly won't work if you need x to the 3/4 power though.

this is a mess:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

math is <cmath> in c++
stdio is <cstdio> in c++
string.h is c-strings, to be avoided in c++ if you can. its also <cstring>
it is extra clunky to see vectors and c-strings mixed together without a good reason.
math.h is repeated.
and you guess it, <cstdlib>

assert() is removed in release builds. Its a tool to find problems.
run in debug mode and find the assertion that is failing, what does it say? Where is it?
it should be clear what to fix. Asserts are put into some VS tools to warn you that working code may still have a hidden bug that can bite later. Some of them are more critical than others.


Last edited on
1
2
3
4
5
	for (i = 1; i <= Data.size(); i++)
	{
		Data[i] = rand() % 2;
		std::cout << Data[i] % 2 << " ";
	}

The range of Data is [ 0 .. Data.size() ), but you're using [ 1, ... Data.size() ], and going beyond the end.

It's conventional to write it like this:
1
2
3
4
5
6
7
8
9
	for (i = 0; i < 4; ++i)                                                               
	{                                                                                       
		Data.push_back(i + 1);
	}
	for (i = 0; i < Data.size(); ++i)
	{
		Data[i] = rand() % 2;
		std::cout << Data[i] % 2 << " ";
	}
Last edited on
Topic archived. No new replies allowed.