Reputation: 361
I'm having a problem with dynamic memory allocations in c++. I have to write a function that solves a maze stored in a .dat file. The walls are made of # separated by a space, and some points are words that need to be read in to an arbitrary length c string. This c string is then stored in the maze array. My problem is that my c strings keep overwriting previous ones in memory. How can I tell the program not to overwrite certain blocks of memory?
This is the function the initialises the maze array:
int LoadMaze(Maze& maze, int& width, int& height, char fname[])
{
ifstream ifs(fname);
int stringLength;
char inputChar;
char* newCString;
if (ifs.good())
{
ifs >> width >> height;
maze = new char*[width*height];
for (int i=0;i<width*height;i++)
{
stringLength = 0;
inputChar = '1';
while(inputChar != ' ')
{
inputChar = ifs.get();
if(inputChar != ' ' && inputChar != '\n')
{
newCString = resizeChar(newCString, stringLength);
newCString[stringLength++] = inputChar;
}
}
//maze = resizeMaze(maze, i);
maze[i] = newCString;
}
ifs.close();
return 1;
}
else
{
cerr << "File not found." << endl;
return 0;
}
}
Since the C string has to be an arbitrary length, resizeChar increases the cstring size by one. Then the pointer to that cstring is stored in maze.
char* resizeChar(char* stringStart, int oldSize)
{
int counter = 0;
char* tempPtr = new char[oldSize + 1];
for(counter = 0; counter < oldSize; counter++)
{
*(tempPtr + counter) = *(stringStart + counter);
}
delete[] stringStart;
return (tempPtr);
}
Upvotes: 1
Views: 2283
Reputation: 182883
The question is how do I stop new values of newCString from being written in the same memory location as previous ones?
If you replace the old value of a variable with a new one, then the old value will be overwritten because a variable, during its life, does not move in memory. If you don't want to change the value, simply don't write code that changes it. Set the value of newCString
to the value you want it to hold and do not change its value from then one.
Upvotes: 0
Reputation: 141658
You are passing an uninitialized value to your function:
char* newCString;
....
newCString = resizeChar(newCString, stringLength);
To fix this you need to give newCString
a sensible initial value, and make sure that resizeChar
can handle that scenario.
It would be better to initialize newCString
each time around the loop. That also avoids the problem that you are using the same buffer for every row of the maze.
Another major problem is that you never null-terminate the strings you are building. So once you have gone maze[i] = newCString;
, that row is just pointing to some characters but you have lost the information of how many characters are in the string. And if you try to output this string then you will buffer overflow and start outputting garbage.
You need to allocate 1 more byte than the number of characters in the string, and make the last one of those be '\0'
.
Upvotes: 2