Breakpoint/heap error in code

Hello

I'm encountering an error when compiling mine application. It compiles fine but when I run it, I get two errors:
1) ConsoleApplication.exe has triggered a breakpoint.
2) I also get something about heap errors.

I've understood it had something to do with memory?

The error is somewhere in this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	int deleteFile(string fileToDelete) {
		char *cstr = new char[fileToDelete.length()];
		strcpy_s(cstr, 256, fileToDelete.c_str());

		ifstream fileExistance(cstr);

		if (fileExistance) {
		fileExistance.close();
			if (remove(cstr)) {
				return 0;
			} else {
				return 1;
			}
		} else return 2; fileExistance.close();
	}


Someone able to find the error, and explain it to me?

Thanks for reading,
Niely
strcpy_s(cstr, 256, fileToDelete.c_str());

The second parameter should be the size of the destination buffer, why do you assume it is 256. In this case it would be fileToDelete.length().

I would say the more important question is why are you writing it like this? You can do all file handling with just strings which would be much safer.
char *cstr = new char[fileToDelete.length()];
It would not be large enough to hold whole fileToDelete string: you still need place for null terminator.

In your case there are no reasons to even have that temporary buffer (which you leak): as James2250 said, filestream constructor takes string as argument too (and you can use c_str if you are using decades old compiler) and you can safely pass c_str to remove too.
Thanks for the help and advise all! :)
I had to use FileToDelete.length() +1 though, otherwise my buffer was to small. :)
(Probably nullspace).
Topic archived. No new replies allowed.