a simple delete[] causes problems

Hi guys,
I'm new to this forum.
I'm trying to understand the way "delete" and "new" works.
I wrote a simple program that convert CAPS letter to regular ones.
The main calls a function that ues the "new" command and I need to delete that new pointer after the function returns the value.
I don't why but the delete command causes a "Heap corruption" crash.
Can you please help me out ?
Thank you very much guys...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string.h>

using namespace std;

char* toLower(char* str);

void main()
{
	char string[10] = "WiskyGoGo";
	char* deleteMe;

	deleteMe = toLower(string);
	cout << deleteMe << "\n";

	delete[] deleteMe;
}

char* toLower(char* str)
{
	char* resultStr;
	int stringSize, i;
	int distance = (int)('a' - 'A');

	stringSize = strlen (str);
	resultStr = new char[stringSize];

	strcpy (resultStr, str);

	for (i=0; i <= stringSize-1; i++)
	{
		if ((resultStr[i] >= 'A') && (resultStr[i] <= 'Z'))
			resultStr[i] = (char) ((int)(resultStr[i])+distance);
	}

	return resultStr;
}
1. main must return int (otherwise most people won't be able to compile your program)
2. replace resultStr = new char[stringSize]; with resultStr = new char[stringSize+1]; Your strcpy wrote past the end of the memory block allocated by new[] and thus corrupted the heap.
3. don't use arrays of char to handle strings
Cubbi, you are sharp as a razor !

Thanks a lot for your fast help.

I'm a computer science student and it's my first real programming course.

The first courses were all about math and stuff.

So now I have to follow the basic rules of my teacher so I can't do much with 1 and 3, but it's good to know.

And about comment No. 2, I didn't know that, but now I do, so again, thank you man...

Guy
Topic archived. No new replies allowed.