Archived

This topic is now archived and is closed to further replies.

pag

Why does this crash?

Recommended Posts

int main(int, char**)
{
	int** a = new int*[10];
	for(int i=0; i<10; i++)
		a[i] = new int[10];
		
	int* itr = &a[0][0];
	for(int i=0; i<100; i++)
	{
	        *itr = 10;
		itr++;
	}
	
	std::cin.ignore();
	for(int i=0; i<10; i++)
		delete[] a[i];      // crashes here

		
	delete [] a;
	return 0;
}

Share this post


Link to post
Share on other sites
bcuz you cant expect that new allocates everytime memory directly behind the previous new allocation + debug is storing extrastuff after the allocated block, so this will write into memory it shouldnt write to:

for(int i=0; i<100; i++){
*itr = 10;
itr++;
}

edit: by deleting a damaged block (written outside the allocated block) you get an error saying something with block damaged...


T2k

[edited by - T2k on October 23, 2003 12:55:22 PM]

Share this post


Link to post
Share on other sites
You are exceeding the limit of your array. You have an array of 10 pointers, but your loop goes up to 99!
What you have is not the same as an static 10*10 array, but even then your iteration would not be the "clean" way.

Share this post


Link to post
Share on other sites
Hello pag,

I assume that line with
for(int i=0; i<100; i++)
was a typo and should have been
for(int i=0; i<10; i++)

if not memory overwrite could be the cause.

Ahh yes that is your problem right there.

you create a arrary of 10 pointers to int.

then you went in and create arrays of 10 ints for each pointer.

but each of these 10 array could be anywere in memory that are not all in one big block.

therfore you can''t do:
int* itr = &a[0][0];
for(int i=0; i<100; i++)
{
*itr = 10;
itr++;
}

very bad over writing memory you did not allocate.

shame on you, go to your room

the only way it would work for your way is if you went in and did a new int[100] and then assin each a to the address of evey 10th int in this int[100];

Do you get what I try to write here

Lord Bart

Share this post


Link to post
Share on other sites