Using Pow in C++ MinGW. Works hard coded but not with variables - c++

This is hopefully a simple linker issue but I've spent hours searching and haven't moved forward in that time. I'm trying to use
#include <cmath>
double aA = 2;
double result = pow((double)2.0,(double)aA);
I get no error messages and it compiles without issue. But an unrelated grid I'm drawing with openGL doesn't display. If i substitute the aA for 2 then it displays the grid. Like
#include <cmath>
double aA = 2;
double result = pow((double)2.0,(double)2);
This outputs 4 as expected. The previous example outputs nothing. It's as if the program hangs but there are no errors.
This computation isn't used anywhere and in fact just sits in main (or anywhere else) and the variables are unique and are unused.
I'm using code::blocks and minGW GNU GCC compiler in Windows 7. -g -Wall - WExtra
Rendering with glew + freeglut and everything else works until i use a variable with pow.
I've tried every combination of casting I can think of and I've tried powf with the exact same result. I'm using sqrt and other functions so believe that the inclusion is working. I've also tried math.h but get the same problem.
I have never wished to see an error message from a compiler more so than I do right now.
So 1. Why am I not getting an error when it looks like its stopping the whole program in its tracks?
And 2. What have I missed to get pow() working with variables?
Update : After creating a new project and trying it out I have no issues so there must be something in my setup that's interfering. I'll keep experimenting. Thanks for the quick responses things sure move fast around here!
Update 2:
Very strange.
float aAs = 1.0;
float amplitudeA = (float)pow((float)2.,(float)aAs);
char str[50];
int test = (int) (amplitudeA);
sprintf (str, "out - %d", test);
MessageBox(NULL,str,NULL,NULL);
This outputs 2 in the message box. Then my grid draws and the program behaves. If i comment out only the message box like so:
float aAs = 1.0;
float amplitudeA = (float)pow((float)2.,(float)aAs);
char str[50];
int test = (int) (amplitudeA);
sprintf (str, "out - %d", test);
//MessageBox(NULL,str,NULL,NULL);
No drawing of my grid. What could be causing this?
char str[50];
int test = (int) (1);
sprintf (str, "out - %d", test);
MessageBox(NULL,str,NULL,NULL);
float aAs = 1.0;
float amplitudeA = (float)pow((float)2.,(float)aAs);
Swapping the message box over recreates the issue. No grid drawn. It's as if focus needs to be taken away from the program when I'm using a variable in pow. I'm completely baffled.
Another Update : I temporarily got around it by writing my own simple powerOf function. But now I'm having the same issue with the cos() function.
Can anyone tell me if there is something wrong with that image? This issue has to stem from incorrect linking. Is that what you would expect from hovering over coz in code::blocks with gcc?
This a error that occurs only when running through the program with a bad cos call. Interesting that I've been using cos for camera calculations since I started this app with no issue.
Error #667: UNADDRESSABLE ACCESS: reading 0x00000003-0x00000007 4 byte(s)
# 0 ntdll.dll!RtlImageNtHeader +0x124c (0x77ca43d0 <ntdll.dll+0x343d0>)
# 1 ntdll.dll!RtlImageNtHeader +0x422 (0x77ca35a7 <ntdll.dll+0x335a7>)
# 2 ntdll.dll!RtlImageNtHeader +0x30d (0x77ca3492 <ntdll.dll+0x33492>)
# 3 KERNEL32.dll!HeapFree +0x13 (0x775e14dd <KERNEL32.dll+0x114dd>)
# 4 atioglxx.dll!atiPPHSN +0x11afaa (0x66538f3b <atioglxx.dll+0xeb8f3b>)
# 5 atioglxx.dll!DrvSwapBuffers +0x33fb (0x6569b9cc <atioglxx.dll+0x1b9cc>)
# 6 atioglxx.dll!DrvSwapBuffers +0x3cad (0x6569c27e <atioglxx.dll+0x1c27e>)
# 7 atioglxx.dll!DrvSwapBuffers +0x7c57 (0x656a0228 <atioglxx.dll+0x20228>)
# 8 atioglxx.dll!DrvSwapBuffers +0x12c (0x656986fd <atioglxx.dll+0x186fd>)
# 9 atioglxx.dll!DrvValidateVersion +0x28 (0x65697c19 <atioglxx.dll+0x17c19>)
#10 OPENGL32.dll!wglSwapMultipleBuffers +0xc5d (0x66c8af0b <OPENGL32.dll+0x3af0b>)
#11 OPENGL32.dll!wglSwapMultipleBuffers +0xe45 (0x66c8b0f3 <OPENGL32.dll+0x3b0f3>)
Note: #0:00:05.233 in thread 3136
Note: instruction: mov 0x04(%ecx) -> %ecx

Solved. There was an uninitialized variable that was sitting at the bottom of the vertex buffer object I was using to draw the grid. For whatever reason feeding a variable to one of the math functions caused unexpected results in this buffer object.
Thanks to Angew an Kos for pointing me towards memory.

Related

Declaring variables in Python 2.7x to avoid issues later

I am new to Python, coming from MATLAB, and long ago from C. I have written a script in MATLAB which simulates sediment transport in rivers as a Markov Process. The code randomly places circles of a random diameter within a rectangular area of a specified dimension. The circles are non-uniform is size, drawn randomly from a specified range of sizes. I do not know how many times I will step through the circle placement operation so I use a while loop to complete the process. In an attempt to be more community oriented, I am translating the MATLAB script to Python. I used the online tool OMPC to get started, and have been working through it manually from the auto-translated version (was not that helpful, which is not surprising). To debug the code as I go, I use the
MATLAB generated results to generally compare and contrast against results in Python. It seems clear to me that I have declared variables in a way that introduces problems as calculations proceed in the script. Here are two examples of consistent problems between different instances of code execution. First, the code generated what I think are arrays within arrays because the script is returning results which look like:
array([[ True]
[False]], dtype=bool)
This result was generated for the following code snippet at the overlap_logix operation:
CenterCoord_Array = np.asarray(CenterCoordinates)
Diameter_Array = np.asarray(Diameter)
dist_check = ((CenterCoord_Array[:,0] - x_Center) ** 2 + (CenterCoord_Array[:,1] - y_Center) ** 2) ** 0.5
radius_check = (Diameter_Array / 2) + radius
radius_check_update = np.reshape(radius_check,(len(radius_check),1))
radius_overlap = (radius_check_update >= dist_check)
# Now actually check the overalp condition.
if np.sum([radius_overlap]) == 0:
# The new circle does not overlap so proceed.
newCircle_Found = 1
debug_value = 2
elif np.sum([radius_overlap]) == 1:
# The new circle overlaps with one other circle
overlap = np.arange(0,len(radius_overlap), dtype=int)
overlap_update = np.reshape(overlap,(len(overlap),1))
overlap_logix = (radius_overlap == 1)
idx_true = overlap_update[overlap_logix]
radius = dist_check(idx_true,1) - (Diameter(idx_true,1) / 2)
A similar result for the same run was produced for variables:
radius_check_update
radius_overlap
overlap_update
Here is the same code snippet for the working MATLAB version (as requested):
distcheck = ((Circles.CenterCoordinates(1,:)-x_Center).^2 + (Circles.CenterCoordinates(2,:)-y_Center).^2).^0.5;
radius_check = (Circles.Diameter ./ 2) + radius;
radius_overlap = (radius_check >= distcheck);
% Now actually check the overalp condition.
if sum(radius_overlap) == 0
% The new circle does not overlap so proceed.
newCircle_Found = 1;
debug_value = 2;
elseif sum(radius_overlap) == 1
% The new circle overlaps with one other circle
temp = 1:size(radius_overlap,2);
idx_true = temp(radius_overlap == 1);
radius = distcheck(1,idx_true) - (Circles.Diameter(1,idx_true)/2);
In the Python version I have created arrays from lists to more easily operate on the contents (the first two lines of the code snippet). The array within array result and creating arrays to access data suggests to me that I have incorrectly declared variable types, but I am not sure. Furthermore, some variables have a size, for example, (2L,) (the numerical dimension will change as circles are placed) where there is no second dimension. This produces obvious problems when I try to use the array in an operation with another array with a size (2L,1L). Because of these problems I started reshaping arrays, and then I stopped because I decided these were hacks because I had declared one, or more than one variable incorrectly. Second, for the same run I encountered the following error:
TypeError: 'numpy.ndarray' object is not callable
for the operation:
radius = dist_check(idx_true,1) - (Diameter(idx_true,1) / 2)
which occurs at the bottom of the above code snippet. I have posted the entire script at the following link because it is probably more useful to execute the script for oneself:
https://github.com/smchartrand/MarkovProcess_Bedload
I have set-up the code to run with some initial parameter values so decisions do not need to be made; these parameter values produce the expected results in the MATLAB-based script, which look something like this when plotted:
So, I seem to specifically be having issues with operations on lines 151-165, depending on the test value np.sum([radius_overlap]) and I think it is because I incorrectly declared variable types, but I am really not sure. I can say with confidence that the Python version and the MATLAB version are consistent in output through the first step of the while loop, and code line 127 which is entering the second step of the while loop. Below this point in the code the above documented issues eventually cause the script to crash. Sometimes the script executes to 15% complete, and sometimes it does not make it to 5% - this is due to the random nature of circle placement. I am preparing the code in the Spyder (Python 2.7) IDE and will share the working code publicly as a part of my research. I would greatly appreciate any help that can be offered to identify my mistakes and misapplications of python coding practice.
I believe I have answered my own question, and maybe it will be of use for someone down the road. The main sources of instruction for me can be found at the following three web pages:
Stackoverflow Question 176011
SciPy FAQ
SciPy NumPy for Matlab users
The third web page was very helpful for me coming from MATLAB. Here is the modified and working python code snippet which relates to the original snippet provided above:
dist_check = ((CenterCoordinates[0,:] - x_Center) ** 2 + (CenterCoordinates[1,:] - y_Center) ** 2) ** 0.5
radius_check = (Diameter / 2) + radius
radius_overlap = (radius_check >= dist_check)
# Now actually check the overalp condition.
if np.sum([radius_overlap]) == 0:
# The new circle does not overlap so proceed.
newCircle_Found = 1
debug_value = 2
elif np.sum([radius_overlap]) == 1:
# The new circle overlaps with one other circle
overlap = np.arange(0,len(radius_overlap[0]), dtype=int).reshape(1, len(radius_overlap[0]))
overlap_logix = (radius_overlap == 1)
idx_true = overlap[overlap_logix]
radius = dist_check[idx_true] - (Diameter[0,idx_true] / 2)
In the end it was clear to me that it was more straightforward for this example to use numpy arrays vs. lists to store results for each iteration of filling the rectangular area. For the corrected code snippet this means I initialized the variables:
CenterCoordinates, and
Diameter
as numpy arrays whereas I initialized them as lists in the posted question. This made a few mathematical operations more straightforward. I was also incorrectly indexing into variables with parentheses () as opposed to the correct method using brackets []. Here is an example of a correction I made which helped the code execute as envisioned:
Incorrect: radius = dist_check(idx_true,1) - (Diameter(idx_true,1) / 2)
Correct: radius = dist_check[idx_true] - (Diameter[0,idx_true] / 2)
This example also shows that I had issues with array dimensions which I corrected variable by variable. I am still not sure if my working code is the most pythonic or most efficient way to fill a rectangular area in a random fashion, but I have tested it about 100 times with success. The revised and working code can be downloaded here:
Working Python Script to Randomly Fill Rectangular Area with Circles
Here is an image of a final results for a successful run of the working code:
The main lessons for me were (1) numpy arrays are more efficient for repetitive numerical calculations, and (2) dimensionality of arrays which I created were not always what I expected them to be and care must be practiced when establishing arrays. Thanks to those who looked at my question and asked for clarification.

Malloc Error: OpenCV/C++ while push_back Vector

I try to create a Descriptor using FAST for the Point detection and SIFT for building the Descriptor. For that purpose I use OpenCV. While I use OpenCV's FAST I just use parts of the SIFT code, because I only need the Descriptor. Now I have a really nasty malloc Error and I don't know, how to solve it. I posted my code into GitHub because it is big and I dont really know where the Error comes from. I just know, that it is created at the end of the DO-WHILE-Loop:
features2d.push_back(features);
features.clear();
candidates2d.push_back(candidates);
candidates.clear();
}
}while(candidates.size() > 100);
As you can see in the code of GitHub I already tried to release Memory of the Application. Xcode Analysis says, that my Application uses 9 Mb memory. I tried to debug the Error but It was very complicated and I haven't found any clue where the Error comes from.
EDIT
I wondered if this Error could occur because I try to access the Image Pixel Value passed to calcOrientationHist(...) with img.at<sift_wt>(...) where typdef float sift_wt at Line 56, and 57 in my code, because normally the Patch I pass outputs the type 0 which means it is a CV_8UC1 But well, I copied this part from the sift.cpp at Line 330 and 331 Normally the SIFT Descriptor should also have a Grayscale image or not?
EDIT2
After changing the type in the img.at<sift_wt>(...)Position nothing changed. So I googled Solutions and landed at the GuardMalloc feature from XCode. Enabling it showed me a new Error which is probably the Reason I get the Malloc Error. In line 77 of my Code. The Error it gives me at this line is EXC_BAD_ACCESS (Code=1, address=....) There are the following lines:
for( k = 0; k < len; k ++){
int bin = cvRound((n/360.f)+Ori[k]);
if(bin >= n)
bin -=n;
if(bin < 0 )
bin +=n;
temphist[bin] += W[k]*Mag[k];
}
The Values of the mentioned Variables are the following:
bin = 52, len = 169, n = 36, k = 0, W, Mag, Ori and temphist are not shown.
Here the GuadMalloc Output (sorry but I dont really understand what exactly it wants)
GuardMalloc[Test-1935]: Allocations will be placed on 16 byte boundaries.
GuardMalloc[Test-1935]: - Some buffer overruns may not be noticed.
GuardMalloc[Test-1935]: - Applications using vector instructions (e.g., SSE) should work.
GuardMalloc[Test-1935]: version 108
Test(1935,0x102524000) malloc: protecting edges
Test(1935,0x102524000) malloc: enabling scribbling to detect mods to free blocks
Answer is simpler as thought...
The Problem was, that in the calculation of Bin in the For-loop the wrong value came out. Instead of adding ori[k] it should be a multiplication with ori[k].
The mistake there resulted in a bin value of 52. But the Length of the Array that temphist is pointing to is 38.
For all who have similar Errors I really recomment to use GuardMalloc or Valgrind to debug Malloc Errors.

Why is GLSL log returning the wrong result? (Intel Driver)

I am doing some maths on the GPU and reading the result.
And I am getting the wrong value From log. I have verified this for values 0 - 10, 20, 30, 40.
If I hard code the value (as you can see bellow under verify) I get the right result spat out. However if I use log with the hard coded value that should return the same result, I get the wrong result spat out.
This is the kind of thing I have been doing in my function.
vec4 IScale(vec4 value)
{
switch(uScaleType_i)
{
case Log:
//value = log(value);
value = vec4(1,1,1,1);
value.r = log(5);
//verifiy
//value.r = 0.698970004
break;
case Sqrt:
value = sqrt(value);
break;
case None:
break;
}
return value;
}
I am wondering is there any sense here. I have added the results of what I am getting back into excel and done a graph. At first Its almost like its double the correct value but its not quite that clean, it gets further and further away.
Is there any other explanation for this other than a driver issue? I cant think of anything else to check!
And if so how can i possibly work around it, other than refactoring my code to do it on the CPU? And why can't I find evidence online to back this up? I am completely utterly baffled!
I am running on a laptop with:
(Intel(R) HD Graphics 4000 with 132 ext.)
p.s. Sqrt is fine and I get the values I would expect.
p.p.s I checked, I have not accidentally created a function called "log"
I believe you are tripping over the base used for the log. In Excel the base is 10 however in glsl it is e.
To get the right result you should divide the result with the log of the base you want.
value = log(value)/log(10);
Or in excel you can use LN(RC[-1])
This is as per the specification. log() will return the natural logarithm, i.e. the logarithm to the base e. Not the base 10 logarithm.

c++ local variable gets overwritten (but only on some notebook)

I am facing some strange behaviour appearing only on some notebook.
I am developing in c++ using msvc 2012 and the qt framework.
I will try to sum up the problem and i am hoping that someone has any idea what the problem could be or what i could try to find out..
Generally it's the following problem:
void myclass::foo()
{
const double value1 = 100.0;
double value2;
value2 = some_function_returning_double();
if(value1 > value2)
{
//__ do something
}
}
The problem is that the condition fails as the local variable gets overwritten.
If I do some debug output i can see that variable value1 is not 100.0 anymore but some random value .. so that the comparison randomly fails ..
One thing i figured out is that everything just works fine if i don't use local variables. If i set up value1 and value2 as member variables of my class everything works without problems, but that can't be the solution.
Now the strange thing is that this error does only occur on some notebook (some mobile i5 cpu).
On my machine (i5) and on many other notebooks (even other mobile i5) everything just works fine.
I know that you won't be able to solve my problem with this little information i can offer here, but maybe some of you has any hint what the problem could be and what i could try to solve this.
Many thanks in advance.
In visual studio 2012, add a data breakpoint (debug->new breakpoint->new data breakpoint) on the address of the variable that gets overwritten.
First, break at the start of the function.
Then set the data breakpoint: just type &value1 in the "New breakpoint` the input box.
Then it should break just after the value has been modified, and you should see the culprit.
Data breakpoints are a very powerful tool, that helped me found nasty bugs very quickly.

cvHaarDetectObjects(): "Stack aound the variable 'seq_thread' was corrupted."

I have been looking in to writing my own implementation of Haar Cascaded face detection for some time now, and have begun with diving in to the OpenCV 2.0 implementation.
Right out of the box, running in debug mode, Visual Studio breaks on cvhaar.cpp:1518, informing me:
Run-Time Check Failure #2 - Stack aound the variable seq_thread was corrupted.
It seems odd to me that OpenCV ships with a simple array out-of-bounds problem. Running the release works without any problems, but I suspect that it is merely not performing the check and the array is exceeding the bounds.
Why am I receiving this error message? Is it a bug in OpenCV?
A little debugging revealed the culprit, I believe. I "fixed" it, but this all still seems odd to me.
An array of size CV_MAX_THREADS is created on cvhaar.cpp:868:
CvSeq* seq_thread[CV_MAX_THREADS] = {0};
On line 918 it proceeds to specify max_threads:
max_threads = cvGetNumThreads();
In various places, seq_thread is looped using the following for statement:
for( i = 0; i < max_threads; i++ ) {
CvSeq* s = seq_thread[i];
// ...
}
However, cxmisc.h:108 declares CV_MAX_THREADS:
#define CV_MAX_THREADS 1
Hence, the declaration of seq_thread must never be allowed to exceed size 1, yet cvGetNumThreads() returns 2 (I assume this reflects the number of cores in my machine).
I resolved the problem by adding the following simple little statement:
if (max_threads > CV_MAX_THREADS) max_threads = CV_MAX_THREADS;
Does any of this make sense?