2

i have been programming in C/C++ for my academic courses a lot and was under the impression i had a pretty good grasp of it. but lately i had to work in a bluetooth application that had a server and client implementation in a Linux box and an embedded system. i learned bluez bluetooth API, socket/network programming and coded it.

however i ran into a lot of problems with memory leaks and segmentation faults and other memory related errors along the way.as the code grew more complex i all but lost control of the pointers and threads and sockets. this got me wondering that i had a lot to learn that they didn't say in the basic C/C++ books. so i wanted to ask for the resources that are available that'll help be code better in a professional way in C/C++ .especially for the Linux/Mac environment (gcc compiler).

Edit: changed C to C++ because of the confusion it was creating.

sfactor
  • 12,592
  • 32
  • 102
  • 152
  • 21
    The first step towards learning to program C _or_ C++ the "right way" is to stop thinking of the pair as a single language and realize that the two are quite different, especially when it comes to writing good code. – James McNellis May 16 '10 at 00:22
  • @james yes u r correct in pointing that out to me. i was mainly referring to handling the memory and threads. the C is there bcoz i presume much of that functionality in C++ has been derived from C as C is a subset of C++ in my amateurish way of thinking. a lot of time i find C++ projects having some pure C code in there as well. but to make it clear it is C++ i want to learn better. – sfactor May 16 '10 at 00:29
  • 1
    I think that proper way to learn C++ would be coding for fun for a few years. Nothing beats experience, and you learn best when you work on something complicated and enjoy it. I'd say that if "you lost control of pointers", then you are pretty green. You need more practice, not books. Try to write a game engine from scratch, or something like that. – SigTerm May 16 '10 at 01:51
  • 1
    @David well its your opinion so u r entitled to it, i've got nothing to say abt that...i am someone just starting to venture into the wild world of coding...i realized i needed to learn a lot more than what the basic books n my academic courses taught me...so i wanted to know the opinion of other people who have already been down that road...is that so wrong?...and yeah how ever u may pick your nose its considered bad practice to pick it in public. that is the sort of thing i wished to get some idea about here. – sfactor May 16 '10 at 01:57
  • @sfactor There's nothing *wrong* with it, but this is just a bad question: it's broad (C++ has a HUGE scope), subjective (your "right way" might not be my "right way"), and doesn't ask anything in particular. If you're having problems with memory leaks, show the code you're having issues with. If you're having trouble understanding pointers, ask about how pointers work. But don't ask a hugely broad subjective question that essentially has no answer. – David Titarenco May 16 '10 at 02:20
  • @David That's not a "bad" question, it is a "novice" question. It shouldn't be deleted, but it is possible that no answer will be useful for original poster. – SigTerm May 16 '10 at 03:02
  • 3
    Your written English suggests you don't put enough care and thought into what you write. It may not be true but it's easy to imagine that you write C++ in the same way, which causes your problems. http://catb.org/~esr/faqs/hacker-howto.html#skills4 –  May 16 '10 at 13:25
  • @Paul Hankin Well i am not going to explain my writing abilities to you. This was just a question that came up in my mind and thought this was a good place to ask people willing to share their suggestions. May be its a reason and I should look more in to it. I'm just starting out and there's still a long way to go before I start writing code like someone with impeccable English like you .). – sfactor May 18 '10 at 15:34

10 Answers10

5

This question is too big, way too big.

In short, there's little you can do other than keep going. You're going to get hit by segfaults many more times. The only thing you can do is keep the focus, hunt those bugs tirelessly, and always trust the bug is in your code rather than in the compiler or some solid library you use. When you're stuck, post here you specific, narrow questions with the relevant code attached. We'll help you then.

Now, from here on it really depends on what language you use: C or C++? These are so different words won't suffice. If it's C++ you're on then the first advice I'll give is use RAII all the time. If it's C you're using then always be conscious about what owns that pointer, when and where it frees it, and most importantly where does the pointer point to. Also, always initialize your data, especially pointers. Never mind performance before it's time, except for big-oh performance.

That's it. Other than that, post your specific issues and we'll work them out. That's the Right Way™ to learn.

wilhelmtell
  • 57,473
  • 20
  • 96
  • 131
3

If you malloc and forget to free, you have a memory leak, what else do you need to know to avoid them? It's all about design patterns, these are quite language agnostic though...

Segfaults are another story of course... If you really want to know how to code C properly, go pick up a copy of the C99 standard. I can't begin to be partially confident in anything I write in C unless I know exactly what the standard says about it. Pretty much the same goes for C++.

EDIT If you are just a beginner at C or C++, you might want to read a book on them first, otherwise the standards will probably be hard to understand.

Community
  • 1
  • 1
  • well of course i know to free after i malloc. but i am sure anyone who tried coding a program of any complexity in C++ has run into memory leaks as other factors come into play like global variables and function pointers and threads and all. i just wanted to learn better practices to minimize this. – sfactor May 16 '10 at 00:41
  • @sfactor, C++ annotations is very helpful in this case I think: http://www.icce.rug.nl/documents/cplusplus/cplusplus.html It explains many of the typical dangers in C++, although a lot of the things inherited from C, it doesn't explain, maybe K&R would be good for that. Hmmm, also, threads are a different beast, and C has no native support for them, so it depends on what implementation you are using on how to handle them correctly. Basically as long as your managing locks correctly you are fine. Threads are problematic in any language. – L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳ May 16 '10 at 01:01
3

My starting advice for dealing with memory and correctness issues in your code starts not with the language but with software practise in general:

  • Program a bit at a time, then test.
  • Test, test, test! Unit test wherever feasible. Catch errors early and incrementally.

I've found through hard experience that C and C++ will be sure to punish you, the longer you go without testing your code. I'll bet you've tried to debug enough of these issues to know that finding a problem in an untested code base of nontrivial size can be baffling and painful.

For books that will help you develop discipline along these lines, I recommend as one starting point The Pragmatic Programmer, Andrew Hunt and David Thomas, Addison-Wesley Professional, 1999.

Tips I have specific to C and C++ are:

  • Don't dynamically allocate unless you need to.
  • Watch your dynamic memory allocation (malloc/new) like a hawk. Make sure you've thought out exactly who owns the objects, and is responsible for deleting them, once they've been created – even in the case of exceptions! (That's where Resource Acquisition Is Initialization comes in.) Design your code so that this ownership is logical and predictable.
  • Use Valgrind, Purify, and other such tools to help catch and diagnose memory issues.

The two books on Stack Overflow's Definitive C++ Book Guide and List (an excellent list, btw!) that I think will help you most along these lines are:

Community
  • 1
  • 1
Owen S.
  • 7,665
  • 1
  • 28
  • 44
2

I can't comment on C but with C++, getting a good book SO definitive book guide and starting with smaller projects are a great start to learning proper coding techniques.

Community
  • 1
  • 1
Robb
  • 2,666
  • 4
  • 20
  • 24
1

I see from your comment that you think memory management is the same in C and C++. It's in fact a very different story.

Thanks to exceptions in C++ you get a new and better way of managing the error checking and resource management. The standard practice is called RAII (Resource Acquisition Is Initialization).


For starters read this thread: whats-the-difference-between-c-and-c

And then some fine books: the-definitive-c-book-guide-and-list

Community
  • 1
  • 1
bitc
  • 1,588
  • 13
  • 15
1

A lot of it is going to be learn by experience. You can read and read but many times you just need to dive in. The one thing that I will say is use a symbolic debugger. Setting up breakpoints and seeing exactly what all of your variables are will speed up finding problems and fixing them 10-fold.

Flamewires
  • 380
  • 1
  • 4
  • 15
1

I think it's important to recognize and accept the following early on:

0.) C++ is not a superset of C, C and C++ are two separate languages with distinct differences.

1.) C and C++ are powerful languages, but they are not particularly friendly to the novice programmer.

2.) Successful C/C++ programmers never stop learning. Exploring new material and reviewing what you've already learned is essential to programming in C or C++.

3.) Programming in C or C++ requires not only a knowledge of the language, but also a knowledge of the concepts behind the language, the tools commonly used to develop in the language (debuggers, build toolchains, compilers, libraries/apis, etc).

wash
  • 497
  • 4
  • 7
0

I think @James McNellis makes the best point. Each language has its own strengths and weaknesses. Good programming is utilizing these aspects of a particular tool to complete a job in the most stable and optimized manner you are able. Only after writing many programs will you be able to foresee when is the best time to use a certain methodology and this is the programming wisdom you want and are seeking. So keep writing programs and keep trying to make them better.

RandyMorris
  • 1,264
  • 9
  • 17
0

For resource management and avoiding memory leaks, the RAII pattern and smart pointers are essential in C++. Browsing Marshall Cline's C++ FAQ Lite is also invaluable for learning the nuances of the language.

Wyzard
  • 33,849
  • 3
  • 67
  • 87
0

First, as it as been pointed out, C and C++ are 2 different languages. C++ was created as a superset of C, but both languages evolved since that time and some constructs that are allowed in C are not in C++ and vice versa.

If you want to learn a language, pick one of them first and focus on it. You can't properly learn either of them while studying the other at the same time as you'll just keep confusing them (unless your brain is very differently organized from mine ;) ).

You'll soon realize there are 3 different areas in programming:

  • Technic: how to realize what you have in mind in your language of choice (C++ features Object-Oriented or Generic programming for example)
  • Design Patterns: high-level view of the code / dependencies organization (how to decouple your code so that changing one tiny bit does not have repercussions throughout the project)
  • Algorithmic: Learn about algorithms and data-structures, understand what complexity (time/space) is

Of course, the real difficulty is that the 3 areas interact with each others so that you can't really learn about them in isolation and that's why you need to pick up a programming language to be able to experiment with the last two. But don't focus solely on technic, learning the C or C++ standard by heart won't make you a good programmer, it'll make you a good technician who needs an architect to direct his work.

Thanks to the advent of the Internet, you can probably search for your errors there and ask on websites (such as this one) when you just can't find out by yourself, be they technical errors (compile errors, program crashes) or design / algorithmic errors (though those are difficult to spot since it usually work, it's just either inelegant or slow)

A last word, it's not because it works that it's the only way to do it. You should try and come up with various ways (exploring various paradigms) so that you can increase your experience and get a good feeling of what paradigm use for what task, when they are suitable or clumsy etc...

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722