How to solve C/C++ memory leaking (in Linux)?
My hobby project Med is written in C++. A lot of implementations need to use dynamic memory allocation and instantiation. Because complex data is impractical to be passed by value, like the case of JavaScript object and array. Since C++ doesn’t have garbage collection, it is possible that the developer doesn’t free/delete the dynamically created memory properly.
As in my project Med, the program will retrieve the memory from other process. That means, it needs to make a copy of the scanned memory. And this will involve creating dynamic memory (using new operator). When using the program to filter the memory to get the target result, it needs to get a new copy of memory with the updated values, then compare with the previous copy. The unmatched will need to be discarded (free/delete); the matched will need to replace the old one (also free/delete the old one, because the new one is dynamically allocated).
C++ future
Recently updating my hobby project Med, memory editor for Linux, still under heavy development with various bugs.
In this project, I use several C++1x features (compiled with C++14 standard). Most recent notable feature is multi-threading scanning. In memory scanning, scan through the accessible memory blocks sequentially is slow. Therefore, I need to scan the memory blocks in parallel. To implement this, I have to create multiple threads to scan through the memory blocks.
Closure
In JavaScript, we can create closure like this,
[code language=“javascript”] var foo = (() => { let x = 0; return () => { return x++; } })();
for (var i = 0; i < 10; i++) { var x = foo(); console.log(x); } [/code]
But translating above code into C++, it cannot work as expected for the variable, unless the variable is outside the lambda function.
[code language=“cpp”] // In a function int x; // variable here auto foo = [&x]() { x = 0; return [&x]() { return x++; }; }(); for (int i = 0; i < 10; i++) { int x = foo(); cout « x « endl; } [/code]
C++ revisit
I liked C programming, as it is low level and the compiler is widely available. Using C language can demonstrate the understanding of pointer and memory. You can implement a linked list or a hash table by using C. So that you can understand better how the linked list and hash table work.
But as long as you want to build some end user applications, C language is never a good choice. Choosing a language for our product is important. We do not develop a web application using low level programming language. It is totally impractical.