Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory management in C++.

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:

  1. Printing the array arr after it has been initialized gives me 1 17 times.
  2. Inside someFunc too, I print arr before delete to get the same print as above.
  3. Upon going back into 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.

like image 862
Sriram Avatar asked May 25 '26 04:05

Sriram


1 Answers

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.

like image 123
Marcelo Cantos Avatar answered May 27 '26 17:05

Marcelo Cantos