3

I'm using a C program to control an electrical test system. Our team experienced a serious memory leak recently and were considering switching to C++ for future projects. Could C++ be a solution?

Does C++ have any benefits to avoid memory leaks?

Galik
  • 47,303
  • 4
  • 80
  • 117
J. Shin
  • 79
  • 4
  • 2
    That's like asking "is a car better than a bicycle"? They both have their strengths and weaknesses. And it seems like in this case, the problem isn't with the language but with the code. – grooveplex Feb 16 '19 at 19:27
  • 6
    @grooveplex: Not exactly. C++ has specific features that make it easier to correctly manage memory allocation that are absent in C. Since C is a subset of C++, C++ has more and better features and lacks nothing that C has. – Eric J. Feb 16 '19 at 19:30
  • 1
    For the "opinion-based" votes to close, there is already an answer with specific, factual reasons C++ is better. – Eric J. Feb 16 '19 at 19:31
  • 2
    c++ supports better practices while maintaining most of the low level power, but you're already looking at a major re-write to use them, and there are languages which are designed to fully handle memory management for you (rather than just provide some better features). It could be equally beneficial to fix your code, or go to something completely different. c++ has its strengths, but it's not magic. – Kenny Ostrom Feb 16 '19 at 19:34
  • 6
    C++ does have benefits, but it sounds like you would be better employed in identifying the leaks in your C code - it's entirely possible (and really not that difficult) to write leak-free code in C if you know what you are doing. You can also write leaky code in C++ if you don't know what you are doing. –  Feb 16 '19 at 19:36
  • I thought C++ is better, but I couldn't search the specific, factual reasons. "std::unique_pti" is the reason? Could you share more specific? – J. Shin Feb 16 '19 at 19:39
  • If that's the path you've chosen, and you're just looking for someone to agree, follow the path of https://github.com/isocpp/CppCoreGuidelines – Kenny Ostrom Feb 16 '19 at 19:43
  • 2
    @Eric "lacks nothing that C has" - this is nonsense. To take a single example (there are many others) - VLAs. –  Feb 16 '19 at 19:43
  • 1
    Closing this makes no sense. There is an objectively definitive answer to this question. It is not asking to compare bad C++ programmer to good C programmers. It is asking about **language features**. – Galik Feb 16 '19 at 19:50
  • 1
    In my experience C++ does have potential benefits to avoiding memory leaks, if those facilities are utilized. But so much code does not utilize those facilities (e.g., because the code predates modern C++), that I don't think it can be granted as a point in C++'s favor. If you just use C++ as a better C, and continue to use the code's current procedural idioms, it will be difficult to fully exploit C++'s potential for better memory management. – Eljay Feb 16 '19 at 19:57
  • It is very simple to write *much safer code* using `C++`, I am frequently rewriting portions of historically `C` code using simple automatic resource cleanup techniques. – Galik Feb 16 '19 at 19:59
  • 1
    Sorry, the word "better" in the title is not sufficient to close this question as opinion based. There is a clear issue and question, and there are plenty of objective arguments to answer it. Please consider reopening. – Christophe Feb 16 '19 at 21:11
  • Have you tried to find the leakage with some runtime checking tools like valgrind? Refactorying C code to C++ code to avoid leakage might not be a small task. – stensal Feb 16 '19 at 22:01
  • We fixed the issue and no problem now. But from this experience, a question is arose whether to convert to C++ for the future to reduce memory leak issue. I'm wondering how much memory leak is dependent to the language c and c++. – J. Shin Feb 16 '19 at 23:07
  • @J.Shin C++ may reduce memory leak at the cost of increasing abstraction and complexity. Peformance tuning for C++ code could be tricky. – stensal Feb 17 '19 at 02:41
  • @EricJ. "*C is a subset of C++*" - once upon a time, that was true. But *modern* C and C++ have evolved into really separate languages. While C++ still maintains a certain level of compatibility with C, it doesn't support/allow everything that C does. And some features of C++ have been added to C, but many have not – Remy Lebeau Feb 17 '19 at 09:04

1 Answers1

4

Yes, it is. C++ allows user-defined types that run code when they are destroyed. That means automatic variables can be used to manage allocated memory.

See (for example) std::unique_ptr for a smart pointer that cleans up memory automatically when it goes out of scope.

Furthermore std::unique_ptr adds no overhead to using a raw pointer as it is purely syntactic sugar, the compiler's optimizer strips everything away generating almost identical code to hand crafted manual allocation.

Furthermore, it is not just memory that can be automatically cleaned up you can use std::unique_ptr to close your files for you!

struct FILE_closer{void operator()(std::FILE* fp) const { if(fp) std::fclose(fp); }};
using unique_FILE = std::unique_ptr<FILE, FILE_closer>;

void func()
{
    // this will close when it goes out of scope
    unique_FILE fp(std::fopen("filename.txt", "w"));

    std::fprintf(fp.get(), "hello %s", "world");

    // no need to close fp here!

}

Character string that automatically clean up themselves!

struct malloc_deleter{void operator()(void* p) const { std::free(p); }};
using char_uptr = std::unique_ptr<char, malloc_deleter>;

void func()
{
    char_uptr s((char*) malloc(128));

    std::sprintf(s.get(), "Hello World Number %d\n", 5);

    std::printf(s.get());

    // no need to call free(s) here!!!
}
Galik
  • 47,303
  • 4
  • 80
  • 117
  • 4
    This is correct, but this functionality only helps if you actually use it instead of C-style allocation. Minimally converting an existing program from C to C++ is trivial, but reworking it to use RAII and smart pointers and so on is likely to be much harder. (The fact that the C program currently has memory leaks is not a good sign.) – ruakh Feb 16 '19 at 19:36
  • @ruakh There are many opportunities in `C` code where is it very simple to replace manual allocations using a `std::unique_ptr` or a container like a `std::vector`. I have often converted such code. Obviously not everything is simple but many things are. We don't know the OPs code but it clearly needs reworking. – Galik Feb 16 '19 at 19:40
  • Do downvoters have an explanation or are you just `C` programmers voting for your langage of choice? *(not really what the downvote button is for)* – Galik Feb 16 '19 at 20:11
  • @Galik I didn't downvote, but it was pretty clear that this question would turn out as _opinion based_, downvotes for answers considered as _off-topic_ are natural, – πάντα ῥεῖ Feb 16 '19 at 20:25
  • @πάνταῥεῖ The question is about language features. That is hardly subject to opinion. – Galik Feb 16 '19 at 20:26
  • @Galik I am with you, though it can be achieved with plain c code as well. There's no strict demand that just switching to c++ might immediately solve the issues. – πάντα ῥεῖ Feb 16 '19 at 20:29
  • 1
    @πάνταῥεῖ The thing is `C` has no features to manage dynamic memory for you but `C++` does have such features. This should not be an argument about whether or not one programmer can write code in `C` that has no memory leaks and another programmer can write code in `C++` that does have memory leaks. It is about `C++` having features that helps prevent those leaks. – Galik Feb 16 '19 at 20:32
  • @Galik [least resort](https://stackoverflow.com/questions/6835684/how-can-i-do-automatic-memory-management-in-c) – πάντα ῥεῖ Feb 16 '19 at 20:37
  • 2
    @πάνταῥεῖ Lol, okay, you win. But I will file that in the "sure jan" box. So lets agree that `C` has just as good memory management features as `C++`. After all they have the `Boehm GC`.... I'll delete this answer and retract my "reopen" vote. If `C` programmer really want to believe that `C` has *just as good memory management as `C++`* they are more then welcome to continue under than impression. – Galik Feb 16 '19 at 21:03
  • @Galik , I was considering a down-vote too (but I didn't). I think you make it sound too easy; as the OP's code is known to have memory leaks, it is very improbably that it can be fixed by some straightforward changes as you describe. As others said, C++ offers you features that make it easier to avoid leaks, but bad style and coding errors will not magically disappear by moving to C++. So I think your answer could lead him to wrong understandings. – Aganju Feb 16 '19 at 21:11
  • 1
    @Aganju But the question isn't about `C++` fixing bad programmers, its about `C++` having specific features. Bad programmers is a red herring - we have no idea what his code is like he simply mentioned memory leak problems. I think the real problem is that it is impossible to sensibly discuss `C` and `C++` (or any other languages) because too many people get defensive about their pet language – Galik Feb 16 '19 at 21:20
  • 1
    @Aganju My question is how likely is it to use bad style in a language and what will the extent of due damage be. Most electrical engineers aren't familiar with C++ (in fact, they hardly know C); they are often involved with low level languages. But in general, C++ gives the programmer more options to avoid bad style than C does IMO. – Red.Wave Feb 17 '19 at 06:07