Application not responding

closed account (43RGz8AR)
Can anyone point out to me why this cashes?
So after about 2 hours of trying to figure out why this class keeps making the application stop responding, I've narrowed it down to this one method which writes to a c string using three parameters. I can't figure out why it would cause a crash. It compiles fine in both mingw64 and Windows SDK 7.1. I suspect that it's trying to write past the array's allocated size.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// w = data to write
// n = the length of the data to write
// adr = the address in the c string to start writing at
// s = the size of the total c string
// data = the c string

void virt::write(const char* w, unsigned long n, unsigned long adr){
	if(n < 1){return;}
	if(adr > s){
		n = n + adr;
	}
	char* tmp = new char[s+n];
	for(unsigned long i = 0; i < s; i++){
		tmp[i] = data[i];
	}
	delete data;
	data = tmp;
	for(unsigned long wc = 0; wc < n; wc++){
		data[adr + wc] = w[wc];
	}
	s = unsigned long(adr + n);
}

This is the code that calls this method.
1
2
3
4
5
6
7
8
9
int main(){
	virt io;
	io.write("MLD", 3, 28);

	io.save("file.bin");

	cin.get();
	return 0;
}


Thanks for the help. This is the first time I've had to post a topic because I couldn't figure out my error.
Last edited on
closed account (43RGz8AR)
Never mind people, lol I fail.
Both for loops are trying to copy array items that are not there.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void virt::write(const char* w, unsigned long n, unsigned long adr){
	if(n < 1){return;}
	if(adr > s){
		n = n + adr; // No, I needed a new var besides n
	}
	char* tmp = new char[s+n];
	for(unsigned long i = 0; i < s; i++){
		tmp[i] = data[i];
// if I do this and there is no data[1,2,3,etc] then I'm getting no-land values
	}
	delete data;
	data = tmp;
	for(unsigned long wc = 0; wc < n; wc++){
// well because I changed n to be more then n, so now I'm getting no-land values again
		data[adr + wc] = w[wc];
	}
	s = unsigned long(adr + n);
}


So anyway here's the fixed code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void virt::write(const char* w, unsigned long n, unsigned long adr){
	if(n < 1){return;}
	unsigned long etc = 0;
	if(adr > s){
		etc = n + adr;
	}
	char* tmp = new char[s+n+etc];
	for(unsigned long i = 0; i < s+n+etc; i++){
		if(adr > s){
			tmp[i] = 0x00;
		} else {
			tmp[i] = data[i];
		}
	}
	delete data;
	data = tmp;
	for(unsigned long wc = 0; wc < n; wc++){
		data[adr + wc] = w[wc];
	}
	s = unsigned long(adr + n);
}


Topic archived. No new replies allowed.