0

If I define a custom destructor, do I have to delete every variable manually?

Memory allocated by malloc should be freed in the destructor. How about the pointer to the memory allocated by malloc, and an int?
a.h:

#ifndef A_H
#define A_H
#include <stdlib.h>
#include <iostream>
#include <stdint.h>
using namespace std;

class A{
    public:
    uint32_t  x;
    uint32_t* ar_y;
    A(void);
    ~A(void);
};
#endif

a.cpp:

#include "a.h"
A::A(void){
    x = 0;
    ar_y = (uint32_t*)(malloc(4));
}
A::~A(void){
    // free the memory allocated by malloc
    free(ar_y);
    //Is it ok to do nothing for int* y and int x?
}

test.cpp:

#include "a.h"
int f(void){
    A objA;
    //cout << objA.x << endl;
    //Upon exiting the function
    //destructor of A is called.
}
int main(void){
    uint32_t i;
    // see if memory usage go crazy.
    for (i = 0; i < 10000000000; i++) f();
}

Test result:

memory usage didn't rise crazily.

Cache Staheli
  • 3,510
  • 7
  • 32
  • 51
rxu
  • 1,369
  • 1
  • 11
  • 29

1 Answers1

3

You don't need to do anything for x. You need to take care of deallocating memory pointed to by ar_y.

See What is The Rule of Three? for more info on what you need to do when you allocate memory for member variables in a class.

Since you are in C++ land, prefer to use new and delete operators instead of using malloc and free.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • If I have to allocate memory with 32 bit alignment in Linux ... what is the accepted way to do that in c++? – rxu Jun 28 '16 at 19:24
  • @rxu, See [Dynamic aligned memory allocation in C++11](http://stackoverflow.com/questions/6973995/dynamic-aligned-memory-allocation-in-c11). – R Sahu Jun 28 '16 at 19:27
  • so, I guess that means. 1. write an abstraction layer. or 2. use pointer for allocation of aligned memory when performance is very important. – rxu Jun 28 '16 at 19:54
  • @rxu, that's also what I gathered from that post. I haven't personally dealt with this issue in my work. – R Sahu Jun 28 '16 at 20:01