I am playing a bit with raw pointers on c++, I know that nowadays it is good practices to use smart pointers, but as I am learning c++ on my own, I would like first understand raw pointers before moving to smart pointers.
To play around I have created a fakeClass, and playing in a Xcode console project c++:
/** fakeClass.hpp **/
#ifndef fakeClass_hpp
#define fakeClass_hpp
namespace RPO {
class fakeClass {
private:
int _id;
public:
fakeClass(int id);
~fakeClass();
void message();
}; // end class
} // end namespace
#endif
/** fakeClass.cpp **/
#include "fakeClass.hpp"
#include <iostream>
namespace RPO {
fakeClass::fakeClass(int id) {
_id = id;
std::cout << "Creating object: " << _id << std::endl;
}
fakeClass::~fakeClass() {
std::cout << "Destroying objet: " << _id << std::endl;
}
void fakeClass::message() {
std::cout << "Object: " << _id << std::endl;
}
}
/** main.cpp **/
int main(int argc, const char * argv[]) {
// Instantiate on the stack
RPO::fakeClass fClass(1);
fClass.message();
// Instantiate on the heap
RPO::fakeClass *fClassPointer = new RPO::fakeClass(2);
fClassPointer->message();
fClassPointer = new RPO::fakeClass(3); // Create new object #3, on non deleted pointer
fClassPointer->message();
delete fClassPointer; // Free memory of object #3, but still pointing to the memory address
fClassPointer = nullptr; // pointer is pointing to null right now
fClassPointer->message(); // throws an error
}
Output:
Creating object: 1
Object: 1
Creating object: 2
Object: 2
Creating object: 3
Object: 3
Destroying object: 3
Destroying object: 1
Edited:
Thanks to the revisors, I have been searching but could not find anything, but the question posted by tobi303 answers one of my questions (about why one method is still responding after free the memory), but as I said on the title the main question was about leaks.
As it can be seen, object #2 is never destroyed, so it is an obvious memory leak. I breakpointed after creating the object #3, and typed on Console "leaks pruebaC", following instructions from this question, but I get no leak report... why?
leaks Report Version: 2.0
Process 1292: 147 nodes malloced for 17 KB
**Process 1292: 0 leaks for 0 total leaked bytes.**
Also tried after de fClassPointer = nullptr; with the same result.
So, 2 questions, why the leak didn't showed up? and, do the memory used by an app is freed when the app is terminated? (even if it is a memory leak with no pointers)
Thank you.
PS: extra bonus, when I see examples with "char *myString", should I "delete myString" after?