Code breaking with pointer

My program keeps crashing and/or not printing the correct output. Am I managing dynamic memory incorrectly in this function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	const SomeClass& operator* (const SomeClass& first, const SomeClass& second) {
		char Name_1[41], Name_2[41];
		char* tempPointer = new char[41];
		for (int i = 0; i < 41; i++) {
			tempPointer[i] = first.anotherClass::getName(i);
		}
		strcpy(Name_1, tempPointer);
		delete[] tempPointer;
		tempPointer = new char[41];
		for (int i = 0; i < 41; i++) {
			tempPointer[i] = second.anotherClass::getName(i);
		}
		strcpy(Name_2, tempPointer);
		delete[] tempPointer;


1
2
3
4
5
//get name

	char anotherClass::getName(int i) const {
		return name[i];
	}
Last edited on
Am I managing dynamic memory incorrectly in this function?

Your new and delete[] of tempPointer are fine.

However, your use of C strings and strcpy is suspect. You've not given any indication that getName() is returning null terminated C-strings. If anotherClass::name is not properly null terminated, strcpy will continue copying past the 41 characters allocated for tempPointer.
Use std::string instead of C-strings. Much safer.


Do you mean I should do something like,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	const SomeClass& operator* (const SomeClass& first, const SomeClass& second) {
		int counter = 0;
		char Name_1[41], Name_2[41];
		char* tempPointer = new char[first.anotherClass::getSize() + 1];
		for (int i = 0; i < first.anotherClass::getSize(); i++) {
			tempPointer[i] = first.anotherClass::getName(i);
		}
		strcpy(Name_1, tempPointer);
		delete[] tempPointer;
		tempPointer = new char[second.anotherClass::getSize() + 1];
		for (int i = 0; i < second.anotherClass::getSize(); i++) {
			tempPointer[i] = second.anotherClass::getName(i);
		}
		strcpy(Name_2, tempPointer);
		delete[] tempPointer;


1
2
3
4
5
6
	char Hero::getName(int i) const {
		return name[i];
	}
	int Hero::getSize() const {
		return strlen(name);
	}


Also, how do you mean, std::string?
Last edited on
Hero::getSize() still does not answer my question about whether your C-strings are properly terminated with a null terminator. strlen, like strcpy will keep scanning memory until it finds a null terminator.

Also, how do you mean, std::string?

http://www.cplusplus.com/reference/string/string/
std::string should always be preferred over C-strings in C++.
Topic archived. No new replies allowed.