Question about pointers.

I have a real beginner question about pointers.

I have this example in my notes (not exactly this but I simplefied it for the question).


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

void new_tabel(int * &table) {
	delete [] table; //You do this to be sure you table wasn't pointing to something dynemic and you would lose it now.
	table = new int [10];
	table[5] = 5;
}

int main () {
	int * tab;
	new_tabel(tab); //Can here happen that I delete something that wasn't suposed to be deleted.
	new_tabel(tab); //Now serves the delete to save you from memory leaks
	cout<<tab[5];
}


Now my question is, isn't there a chance that if I declare tab( since the pointer isn't initialized yet it can be pointing to anywhere in my memory) that I delete something the pointer was pointing.
(Ofc in this example I only have 1 table but imagine a bigger one where I would have other arrays ...).
Last edited on
You should get a segmentation error and your program should crash on the first call of delete[]
It's only safe to delete NULL or new[]ed pointers, deleting unitinialized pointers may cause problems
Topic archived. No new replies allowed.