new char[] allocation returning array with wrong size

Dec 24, 2017 at 5:08pm
Hello!
I'm sriting a program, for which I wrote a small function to add a character(c) at the end of an input c string (src). Pretty basic stuff.
Here's the code I wrote.
However there's a problem which I have no idea why it could be happening.
the line
src = new char[strlen(src) + 1];
seems to allocate different number of characters to the pointer src than it is intended, even though strlen(toDel) + 1 returns the right amount of characters when executed on its own.

for example, when the input is consisting of 5 letters - hello for example, it will return that after new allocation

strlen(src) // = 10;

Basically doubling the numebr of needed characters.
Any help would be appreciated!
Merry holidays!
P.S usage of std::string is forbidden

1
2
3
4
5
6
7
8
9
  void addLetter(char*& src, char c) {
	char* toDel = src;
	src = new char[strlen(toDel)+1];
	for (size_t i = 0; i < strlen(toDel); i++) {
		src[i] = toDel[i];
	}
	src[strlen(toDel)] = c;
	delete toDel;
}
Dec 24, 2017 at 5:44pm
You don't reserve space for the null terminator. strlen() computes the length using this character, it can't know what size of array was used for the string.

Also, note that you should use delete[] to release toDel.
Last edited on Dec 24, 2017 at 5:45pm
Dec 24, 2017 at 5:58pm
Yeah, you're right! I forgot strlen used /0 to return the correct value.

IIRC regarding delete, ever since C++ 9/10 delete and delete[] are equivalent regarding deleting memory allocated by arrays
Dec 24, 2017 at 6:00pm
You recall incorrectly.

new -> delete
new[] -> delete[]
Dec 24, 2017 at 6:18pm
After some research, yes you are correct. I should've used delete[]
Dec 25, 2017 at 8:36pm
In addition to allocating enough space for the null-terminator, you have to add the terminator to the new string. Your code doesn't currently do that.

Also you should compute strlen(toDel) once and use the computed value after that. Otherwise you force the poor program to recompute the length a bunch of times.
Dec 29, 2017 at 1:55pm
Make sure you know how to use allocation the right way and control it as it can produce some errors that are pretty are to be detected later. Al though there are programs that might help with it, such as checkmarx, I'd recommend you to practice a lot and know exactly what you do.
Good luck.
Topic archived. No new replies allowed.