pointers and array!!

closed account (4ET0pfjN)
Hi, why can i dynamically allocate memory for integer array, but not string. I mean, when i compile it outputs both: 9909 and "what's up" but crashes if i include the list variable. I'm using windows 7 and a box pops up after displaying 9909 and "what's up" that myprogrm.exe has stopped working...

1
2
3
4
5
6
7
8
9
 int *holder = new int;
	holder[0] = 777;
	holder[3] = 9909;
	
	cout << holder[3] << endl;
	
	string *list = new string;
	list[0] = "hey";
	list[1] = "what's up";
You allocated one element, but you're trying to access the 4th and 2nd element in a non-existing array. How did you expect that to work?
To elaborate, if you want an array, you need to allocate an array:

1
2
3
4
5
6
7
8
9
10
11
12
13
int* holder = new int;  // only gives you 1 int
holder[0] = 777;  // ok
holder[3] = 9909;  // VERY BAD COULD CRASH PROGRAM OR WORSE

delete holder;  // new -> delete
//...

int* foo = new int[4]; // gives you 4 ints
foo[0] = 777;  // ok
foo[3] = 9909;  // also ok
foo[4] = 0xbaad;  // BAD

delete[] foo;  // new[] -> delete[] 
closed account (4ET0pfjN)
so I was playing it safe by assuming next chunk of memory is free right, so short of it is I should always use an array for multiple values to store at once. Ok thanks. And I guess vectors are a step up from dynamically allocated arrays (implies uses pointers) as no troubles with having to manually deallocate memory, right?
Last edited on
I wouldn't call that playing it safe. Your use of holder[3] could very well crash the program or even cause unpredictable bugs later on. list[1] has the same issue; it's possible that the string crashed because it internally relies on dynamic memory but was not initialized properly (but don't write anything that depends on this behavior).

Vectors are almost always better than dynamic arrays. They add a bunch of useful features like optional range checking, iterators, and copy semantics, and they automatically clean up their data, even if an exception is thrown like this:

1
2
3
4
int* arr = new int[10];
vector <int> v(10);
ifstream file("name.txt"); //might throw an exception
delete [] arr


In this case, if an exception is thrown arr will leak memory but v will not.
Topic archived. No new replies allowed.