Hi there,

I'm in the process of moving some code into Visual C++ 2008, the code works fine when compiled with Mingw however crashes when compiled with VC++:

s_cell **cell;
	*cell = (s_cell *) malloc(sizeof(s_cell) * MAP_X);
	for(int loop = 0; loop < MAP_X; loop++)
	{
		cell[loop] = (s_cell *) malloc(sizeof(s_cell) * MAP_Y);
	}

It fails with the following error:

Run-Time Check Failure #3 - The variable 'cell' is being used without being initialized.

and breaks at the *cell = (s_cell *)... line.

I tried replacing the array with a vector however this means a lot of other code needs to be changed and while I have tried nothing appears to happen, I'm sure it's something I'm overlooking in frustration.

Hopefully someone can give me some guidance here.

Recommended Answers

All 4 Replies

cell should not be dereferenced in the first call to malloc(), and the cast is missing a level of indirection.

cell = (s_cell**)malloc(sizeof(s_cell) * MAP_X);

You shouldn't use malloc at all. This is how you do it properly:

s_cell** cell=new s_cell*[MAP_X];
for (int x=0;x<MAP_X;x++)cell[x]=new s_cell[MAP_Y];

Even better is the following:

vector<vector<s_cell> > cell(MAP_X,vector<s_cell>(MAP_Y));

@Aranarth I could kiss you! I usually use malloc over new unless I'm working with a class (this was what I was taught was the correct method), either way that worked flawlessly!

However wouldn't the vector method just put me back into my original position of having to recode other functions?

You only have the parts of the code where vectors are passed to functions and where they are being created. I don't know how much code there is, but it might be worth it. Using vectors automatically takes care of memory management and allows for easy resizing if necessary.

If you use new[], then make sure to use delete[] instead of free to delete your 2D array.

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.