Hello.

I've spent many hours on this code and I cannot figure out why when I either declare "kot" - which will be in the code below or when I call blob_detect() which uses included .cpp with a "new" call (so to speak) I get an error allocating memory. If someone can take a look and please suggest anything. Thank you in advance
PS. Using Visual Studio 2008 in a XP machine.

#include "stdafx.h"
#include "cv.h"
#include <stdio.h>
#include <cstdio>
#include <math.h>
#include <highgui.h>
//#include <time.h>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <ctime>

#include "blob.h"
#include "BlobExtraction.h"
#include "BlobLibraryConfiguration.h"
#include "BlobResult.h"

using namespace std;

#ifndef PATH_MAX
#define PATH_MAX 512
#endif /* PATH_MAX */

void blob_detect(IplImage* img, CvSeq* objects, double thresh, int maxBlobArea, int minBlobArea);


typedef struct ObjectPos
{
    float x;
    float y;
    float width;
	float height;
    int found;    /* for reference */
    int neghbors;
} ObjectPos;

CvSeq* objects;
CvMemStorage* storage;

//int main( int argc, char* argv[] )
int main()
{
	int i, j;
	int saveDetected = 1;
    double scale_factor = 1.2;
    float maxSizeDiff = 1.5F;
    float maxPosDiff  = 0.3F;

    FILE* info;
	char* infoname;
    char* fullname[PATH_MAX];
    char detfilename[PATH_MAX];
    char* filename;
    char detname[] = "det-";

	/* Global Assignments. They should be put interactively eventually*/
	/*double threshold = 100;
	double minBlobArea = 10, maxBlobArea = 300;*/

	filename = "kot1.txt";
	saveDetected = 0;
	infoname = "kot1.txt";

	info = fopen(infoname, "r");

	 if( info != NULL )
	 {
		int x, y, width, height;
        IplImage* img;
        int hits, missed, falseAlarms;
        int totalHits, totalMissed, totalFalseAlarms;
        int found;
        float distance;
        
        int refcount;
        ObjectPos* ref;
        int detcount;
        ObjectPos* det;
        int error;

        int* pos;
        int* neg;

        pos = (int*) cvAlloc( 40 * sizeof( *pos ) );
        neg = (int*) cvAlloc( 40 * sizeof( *neg ) );
        for( i = 0; i < 40; i++ ) { pos[i] = neg[i] = 0; }

        printf( "+================================+======+======+======+\n" );
        printf( "|            File Name           | Hits |Missed| False|\n" );
        printf( "+================================+======+======+======+\n" );
        
        totalHits = totalMissed = totalFalseAlarms = 0;

		storage = cvCreateMemStorage();
		filename = new char;

		while( !feof( info ) )
		{

			//char * imgName = new char[];
			//filename = new char;

			if( fscanf( info, "%s %d", filename, &refcount ) != 2 || refcount <= 0 ){ break;}

			int * kot = new int [333]; //this is the test pointer I'm using to test where the memory allocation starts to fail. If this variable is declared before the if(fscanf(... ...)) it allocates fine. but here it fails. 

            //img = cvLoadImage( fullname );
			img = cvLoadImage( filename, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR );
	
            if( !img ) continue;

			ref = (ObjectPos*) cvAlloc( refcount * sizeof( *ref ) );
            for( i = 0; i < refcount; i++ )
            {
                error = (fscanf( info, "%d %d %d %d", &x, &y, &width, &height ) != 4);
                if( error ) break;
                ref[i].x = 0.5F * width  + x;
                ref[i].y = 0.5F * height + y;
                ref[i].width = sqrtf( 0.5F * (width * width + height * height) );
                ref[i].found = 0;
                ref[i].neghbors = 0;
            }

			if( !error )
            {

				cvClearMemStorage( storage );
				
				objects = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvRect), storage);

/***************************** Insert here detector *********************************/

					blob_detect(img, objects, 100, 10, 100); // this is a function which calls .cpp files that are in the same folder. They are called as I've traced it using the debug functionality in VS '08. There is a function there also that uses 'new' where it fails as well.
               
/************************** END DETECTOR  *****************************************/

			} /* if( !error )*/

		}/*while( !feof( info ) )*/

	 }/* if( info != NULL )*/

	fclose(info);

	return 0;
}

Any help would be greatly appreciated.

Recommended Answers

All 19 Replies

when I call blob_detect() which uses included .cpp
function which calls .cpp files

I'm a tad confused about what you mean by that. Are you saying that you've included the source for the method in another file in your project?

Also while there is still editing time on your old post, put some code tags around your work
It makes it easier to read and preserves the spacing.

I'm a tad confused about what you mean by that. Are you saying that you've included the source for the method in another file in your project?

Partially yes. The method being used has code that I have written (which is in the same .cpp as the main()) and also calls external methods which are being referenced by the following header files.
"#include "blob.h"
#include "BlobExtraction.h"
#include "BlobLibraryConfiguration.h"
#include "BlobResult.h"
I apologize for not being very clear.

See my edit above too :)

filename = new char;
fscanf( info, "%s %d", filename, &refcount )

I'm not sure that this is working the way you want it to. You redeclare a pointer and then you try to write that to a string. It's confusing things and you might be goofing up the placement of something else.

filename = new char;
fscanf( info, "%s %d", filename, &refcount )

I'm not sure that this is working the way you want it to. You redeclare a pointer and then you try to write that to a string. It's confusing things and you might be goofing up the placement of something else.

//filename = new char;
fscanf( info, "%s %d", filename, &refcount )

filename declaration is commented out. that was used for testing so please disregard it. this pointer (filename) will/does get new values every iteration, as fscanf reads the 'info' streaming in a .txt file.

The one outside of the while above is still "live" @ line 98. What does info contain after you go through the loop once? Since if you "new" it filename's not going to point to anything since you have clobbered what was written in it up above.

The one outside of the while above is still "live" @ line 98. What does info contain after you go through the loop once? Since if you "new" it filename's not going to point to anything since you have clobbered what was written in it up above.

I had to allocate new memory for 'filename' as it will be reading a string from the stream (info), so it requires allocation (the compiler also agrees with me here and otherwise at runtime it doesn't :))
After the first iteration, another read is done. What is happening is that a new row in the .txt file is being read and it contains, well, a file name (image file name). So the intent is to simply have 'filename' contain the new image file name. That does, as it is, occur. I can loop through the text file and get the formatted read. The new file names simply overwrite on 'filename'.

I had to allocate new memory for 'filename' as it will be reading a string from the stream (info), so it requires allocation (the compiler also agrees with me here and otherwise at runtime it doesn't :))
After the first iteration, another read is done. What is happening is that a new row in the .txt file is being read and it contains, well, a file name (image file name). So the intent is to simply have 'filename' contain the new image file name. That does, as it is, occur. I can loop through the text file and get the formatted read. The new file names simply overwrite on 'filename'.

To simplify the code even more, the following also generates an error when using 'int * kot = new int;'

#include "stdafx.h"
#include "cv.h"
#include <stdio.h>
#include <cstdio>
#include <math.h>
#include <highgui.h>
//#include <time.h>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <ctime>

#include "blob.h"
#include "BlobExtraction.h"
#include "BlobLibraryConfiguration.h"
#include "BlobResult.h"

using namespace std;

#ifndef PATH_MAX
#define PATH_MAX 512
#endif /* PATH_MAX */

void blob_detect(IplImage* img, CvSeq* objects, double thresh, int maxBlobArea, int minBlobArea);


/*Use this struct to store the objects returned
from the blob detector* - GT*/
typedef struct ObjectPos
{
    float x;
    float y;
    float width;
	float height;
    int found;    /* for reference */
    int neghbors;
} ObjectPos;

CvSeq* objects;
CvMemStorage* storage;

//int main( int argc, char* argv[] )
int main()
{
	int i, j;
	int saveDetected = 1;
    double scale_factor = 1.2;
    float maxSizeDiff = 1.5F;
    float maxPosDiff  = 0.3F;

    FILE* info;
	char* infoname;
    char* fullname[PATH_MAX];
    char detfilename[PATH_MAX];
    char* filename;
    char detname[] = "det-";


	filename = "kot1.txt";
	saveDetected = 0;
	infoname = "kot1.txt";

	info = fopen(infoname, "r");

	 if( info != NULL )
	 {

        
        int refcount;

		filename = new char;

		while( !feof( info ) )
		{
			if( fscanf( info, "%s %d", filename, &refcount ) != 2 || refcount <= 0 ){ break;}

			int * kot = new int;



		}/*while( !feof( info ) )*/

	}/* if( info != NULL )*/

	fclose(info);

	return 0;
}

Hopefully this clears out the clutter

How long are the filenames? I'm afraid that I'm not as versed in the stdio.h functions as I used to be, but I still have a strong suspicion that either you're running over the filename array (or not allocating any room for it in the first place having no filename = new char[something]) or you're not leaving enough room for the null terminus.
I was going through the forums to see if I could find a good concrete example that was similar to yours but I didn't turn up much of anything.
So, I apologize as the only thing I'm confident of is that somewhere in that call you are corrupting memory.

How long are the filenames? I'm afraid that I'm not as versed in the stdio.h functions as I used to be, but I still have a strong suspicion that either you're running over the filename array (or not allocating any room for it in the first place having no filename = new char[something]) or you're not leaving enough room for the null terminus.
I was going through the forums to see if I could find a good concrete example that was similar to yours but I didn't turn up much of anything.
So, I apologize as the only thing I'm confident of is that somewhere in that call you are corrupting memory.

When I go through the step by step debug and 'highlight' the pointer it does in fact read the entire string which is delimited by space as in the fscanf "%s %s". This is also verified by the stdout output. This does occur over and over as there are multiple files in the list. The file names are 26 characters long (all of them, underscores, letters, and numericals).

I do believe you. I'm just confused as to what it could be. Could you put up a representation of a data file so I can run that snippet on my machine?

I do believe you. I'm just confused as to what it could be. Could you put up a representation of a data file so I can run that snippet on my machine?

Hopefully the format carries over. It should be two lines. Each item in the line should be separated by space. Here it is either way:

4_Ticks_LED_Board_0000.bmp 8 272 201 10 11 291 201 10 12 308 202 10 11 280 217 11 10 301 217 10 11 273 233 9 11 289 233 11 10 308 233 10 12
4_Ticks_LED_Board_0001.bmp 8 272 201 10 11 291 201 10 11 308 201 9 11 280 217 11 10 301 217 10 10 273 233 9 10 289 233 10 10 308 233 10 11

Hopefully the format carries over. It should be two lines. Each item in the line should be separated by space. Here it is either way:

4_Ticks_LED_Board_0000.bmp 8 272 201 10 11 291 201 10 12 308 202 10 11 280 217 11 10 301 217 10 11 273 233 9 11 289 233 11 10 308 233 10 12
4_Ticks_LED_Board_0001.bmp 8 272 201 10 11 291 201 10 11 308 201 9 11 280 217 11 10 301 217 10 10 273 233 9 10 289 233 10 10 308 233 10 11

The "4_Ticks_LED_Board_0001.bmp" is where the new line starts.

I will tell you one thing that I did suspect before (I don't know if it has any bearing on the situation but you are writing your numeric values into your filename variable):

filename:4_Ticks_LED_Board_0000.bmp refcount:8
filename:272 refcount:201
filename:10 refcount:11
filename:291 refcount:201
filename:10 refcount:12
filename:308 refcount:202
filename:10 refcount:11
filename:280 refcount:217
filename:11 refcount:10
filename:301 refcount:217
filename:10 refcount:11
filename:273 refcount:233
filename:9 refcount:11
filename:289 refcount:233
filename:11 refcount:10
filename:308 refcount:233
filename:10 refcount:12

Maybe that's what you wanted.

Well this

FILE* info;
	char* infoname;
    char* fullname[PATH_MAX];
    char detfilename[PATH_MAX];
    char* filename;
    char detname[] = "det-";


	filename = "kot1.txt";
	//saveDetected = 0;
	infoname = "kot1.txt";

	info = fopen(infoname, "r");

	 if( info != NULL )
	 {

        
        int refcount;

		filename = new char;

		while( !feof( info ) )
		{
			if( fscanf( info, "%s %d", filename, &refcount ) != 2 || refcount <= 0 ){ break;}
			printf("filename:%s refcount:%d\n",filename,refcount);

			int * kot = new int;



		}/*while( !feof( info ) )*/

	}/* if( info != NULL )*/

	fclose(info);

	return 0;

ran without a hitch so I don't know what to tell you. The allocation seems to take place too.

I will tell you one thing that I did suspect before (I don't know if it has any bearing on the situation but you are writing your numeric values into your filename variable):

filename:4_Ticks_LED_Board_0000.bmp refcount:8
filename:272 refcount:201
filename:10 refcount:11
filename:291 refcount:201
filename:10 refcount:12
filename:308 refcount:202
filename:10 refcount:11
filename:280 refcount:217
filename:11 refcount:10
filename:301 refcount:217
filename:10 refcount:11
filename:273 refcount:233
filename:9 refcount:11
filename:289 refcount:233
filename:11 refcount:10
filename:308 refcount:233
filename:10 refcount:12

Maybe that's what you wanted.

Well this

FILE* info;
	char* infoname;
    char* fullname[PATH_MAX];
    char detfilename[PATH_MAX];
    char* filename;
    char detname[] = "det-";


	filename = "kot1.txt";
	//saveDetected = 0;
	infoname = "kot1.txt";

	info = fopen(infoname, "r");

	 if( info != NULL )
	 {

        
        int refcount;

		filename = new char;

		while( !feof( info ) )
		{
			if( fscanf( info, "%s %d", filename, &refcount ) != 2 || refcount <= 0 ){ break;}
			printf("filename:%s refcount:%d\n",filename,refcount);

			int * kot = new int;



		}/*while( !feof( info ) )*/

	}/* if( info != NULL )*/

	fclose(info);

	return 0;

ran without a hitch so I don't know what to tell you. The allocation seems to take place too.

Well there will be more variables to handle the rest of the digits, however the format is not my concern now, i'm trying to get new memory allocation to happen. I don't know if a setting in the project might throw this off, or a corrupt .dll. When I write fresh code it runs fine. When everything else starts to get added it freaks out. Either way, thank very much you for your help.

I will tell you one thing that I did suspect before (I don't know if it has any bearing on the situation but you are writing your numeric values into your filename variable):

filename:4_Ticks_LED_Board_0000.bmp refcount:8
filename:272 refcount:201
filename:10 refcount:11
filename:291 refcount:201
filename:10 refcount:12
filename:308 refcount:202
filename:10 refcount:11
filename:280 refcount:217
filename:11 refcount:10
filename:301 refcount:217
filename:10 refcount:11
filename:273 refcount:233
filename:9 refcount:11
filename:289 refcount:233
filename:11 refcount:10
filename:308 refcount:233
filename:10 refcount:12

Maybe that's what you wanted.

Well this

FILE* info;
	char* infoname;
    char* fullname[PATH_MAX];
    char detfilename[PATH_MAX];
    char* filename;
    char detname[] = "det-";


	filename = "kot1.txt";
	//saveDetected = 0;
	infoname = "kot1.txt";

	info = fopen(infoname, "r");

	 if( info != NULL )
	 {

        
        int refcount;

		filename = new char;

		while( !feof( info ) )
		{
			if( fscanf( info, "%s %d", filename, &refcount ) != 2 || refcount <= 0 ){ break;}
			printf("filename:%s refcount:%d\n",filename,refcount);

			int * kot = new int;



		}/*while( !feof( info ) )*/

	}/* if( info != NULL )*/

	fclose(info);

	return 0;

ran without a hitch so I don't know what to tell you. The allocation seems to take place too.

Can you try this and let me know if it works for you. From the same code you wrote, remove the printf() and see if memory still allocates. I run it with printf() and it works, if I remove printf() it fails to allocate again. Please let me know if this happens on your end.
Thank you

Indeed it seem to run fine. Runs with the 333 elements too. It's gotta be something else (obviously). Well, at least we learned your input file is not coming in the way it should...
Do you have any strange compiler settings on? Running an old compiler? In the off chance try taking stdio.h out of your includes as you already have cstdio in there.

Failing all else, you could retool that section using fstream methods.

Indeed it seem to run fine. Runs with the 333 elements too. It's gotta be something else (obviously). Well, at least we learned your input file is not coming in the way it should...
Do you have any strange compiler settings on? Running an old compiler? In the off chance try taking stdio.h out of your includes as you already have cstdio in there.

Failing all else, you could retool that section using fstream methods.

I cannot believe it. I changed it to this:

int * tmp = new int;	
			if( fscanf( info, "%s %d", filename, tmp ) != 2 || *tmp <= 0 ){ break;}
			int * kot = new int;

i.e. instead of passing a variable memory reference using &variable, I am passing a pointer, of the same type, and now it's working. I can declare new memory. Thank you for your help.

Awesome. I hope the change will take. Well, I didn't do too much for you but I'm glad it all worked out.
Definitely post back with further questions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.