I have problem with calling delete inside functions. When I allocate memory using new inside function it seem do work, but deleting formerly allocated memory causes throwing of std::bad_alloc. Is it even possible, or can I only free memory under "a" from inside of main?
#include <iostream>
using namespace std;
int size = 5;
void alloc (int* t, char**& a) {
t = new int [size];
a = new char* [size];
for (int i = 0; i < size; ++i)
a[i] = new char [size];
cout << "allocated\n";
}
void realloc (char**& a) {
for(int i = 0; i < size; ++i)
delete [] a[i];
delete [] a;
cout << "deleted\n";
a = new char* [size];
for (int i = 0; i < size+5; ++i)
a[i] = new char [size+5];
cout << "allocated\n";
}
void fillArray (char** a) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
a[i][j] = '.';
}
}
}
void printArray (char** a) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
cout << a[i][j];
}
cout << endl;
}
}
int main() {
int* t;
char** a;
alloc(t, a);
fillArray(a);
printArray(a);
size+=5;
realloc(a);
fillArray(a);
printArray(a);
}
You can call
delete[]from anywhere. Your problems are much more prosaic. You just have a defect in your code.You allocate an array of length
size. Then you incrementsize. Then you do this:And because you incremented
sizealready, your loop runs off the end ofa. You need to use the same value forsizeas was used when you allocated the array.To be quite clear, the following is the flow of execution:
sizeis assigned to the value5.ais allocated with length5.sizeis incremented to the value10.forloop from0tosize-1, that is0to9, and calldelete[] a[i].Clearly the iterations
5to9inclusive are accessing elements ofathat were not allocated. And that's undefined behaviour, and so on.You could fix this by passing the new size to the
reallocfunction as a parameter. Something like this:Obviously you would not modify
sizeoutside of this function. You would call the function like this:Taking it a bit further, you might choose to handle the allocations like this:
All that said, and being perfectly frank, your entire program is a disaster in the making. There are many other errors that I've not covered in this answer. Use standard containers like
std::vectorandstd::string. The standard containers will handle the details of memory allocation, and will do it correctly.