Reputation: 10578
I have the following program:
//simple array memory test.
#include <iostream>
using namespace std;
void someFunc(float*, int, int);
int main() {
int convert = 2;
float *arr = new float[17];
for(int i = 0; i < 17; i++) {
arr[i] = 1.0;
}
someFunc(arr, 17, convert);
for(int i = 0; i < 17; i++) {
cout << arr[i] << endl;
}
return 0;
}
void someFunc(float *arr, int num, int flag) {
if(flag) {
delete []arr;
}
}
When I put the following into gdb
and insert a break point at float *arr ...
, I step through the program and observe the following:
arr
after it has been initialized gives me 1 17 times. someFunc
too, I print arr
before delete
to get the same print as above.main
, when I print arr
, I get the first digit as 0 followed by 16 1.0s. My questions:
1. Once the array has been deleted in someFunc
, how am I still able to access arr
without a segfault in someFunc
or main
?
2. The code snippet above is a test version of another piece of code that runs in a bigger program. I observe the same behaviour in both places (first digit is 0
but all others are the same. If this is some unexplained memory error, how am I observing the same thing in different areas?
3. Some explanations to fill the gaps in my understanding are most welcome.
Upvotes: 2
Views: 223
Reputation: 6287
C++ doesn't check for array boundaries. Only if you access a memory which you are not allowed to you will get segfault
Upvotes: 0
Reputation:
delete
gives the memory back to the OS memory manager, but does not necessarily clears the contents in the memory(it should not, as it causes overhead for nothing). So the values are retained in the memory. And in your case, you are accessing the same memory -- so it will print what is in the memory -- it is not necessarily an undefined behaviour(depends on memory manager)
Upvotes: 2
Reputation: 154047
Once the array has been deleted, any access to it is undefined behavior. There's no guarantee that you'll get a segment violation; in fact, typically you won't. But there's no guarantee of what you will get; in larger programs, modifying the contents of the array could easily result in memory corruption elsewhere.
Upvotes: 2
Reputation: 76876
Dereferencing a pointer after it has been delete
ed is undefined behavior, which means that anything can happen.
Upvotes: 3
Reputation: 6231
Re 1: You can't. If you want to access arr later, don't delete it.
Upvotes: 1
Reputation: 186098
A segfault occurs when you access a memory address that isn't mapped into the process. Calling delete []
releases memory back to the memory allocator, but usually not to the OS.
The contents of the memory after calling delete []
are an implementation detail that varies across compilers, libraries, OSes and especially debug-vs-release builds. Debug memory allocators, for instance, will often fill the memory with some tell-tale signature like 0xdeadbeef.
Upvotes: 3