Pointers are the core to programming languages like C and C++. This at the same time leads to many errors and memory leaks. What are some precautions that must be taken while using pointers in C and C++?
-
3Using pointers as such __doesn't__ lead to any memory leaks. – Paweł Stawarz Feb 13 '14 at 00:02
-
1@PawełStawarz - no it is the "many errors and" that leads to the leaks. :-) – Floris Feb 13 '14 at 00:03
-
C/C++ isn't a language.. It's one or the other. I say this because one of the precautions I like to take is the RAII approach and use a Smart pointer which has nothing to do with C.. otherwise, always check if a pointer is null before accessing and set it to null after deleting in both C and C++. – Brandon Feb 13 '14 at 00:05
-
Making errors while dealing with the pointers also __doesn't__ lead to any memory leaks. Pure pointers (without memory aloccation) can only lead to UB and accessing parts of the memory that aren't ment to :) – Paweł Stawarz Feb 13 '14 at 00:05
-
@PawełStawarz: `int *a; a = malloc(100); a = NULL; ` error. memory leak. – Floris Feb 13 '14 at 00:06
-
In C++ - just avoid pointers (or have them well encapsulated in a class or some shared_ptr/unique_ptr) – Feb 13 '14 at 00:07
-
@Floris that example does __memory allocation__. If you don't allocate memory manually (so - no using `malloc`, `realloc`, `new`, and such), pointers themselves __can't__ cause a memory leak. – Paweł Stawarz Feb 13 '14 at 00:08
-
@PawełStawarz it was the pointer operation `a=NULL;` that was the cause of the memory leak. But I think we are splitting hairs. "Guns don't kill people; people with guns kill people". – Floris Feb 13 '14 at 00:10
-
Take a look at the many resources cited in the sidebar. – vonbrand Feb 13 '14 at 00:13
-
I don't think its a big problem in C++. C yes you actually need to think a lot about it and be careful. In C++ as long as you understand the ownership semantics of the systems its all pretty much automatic and a better version of garbage collection (deterministic cleanup of dynamic objects). The problem here is we still have people teaching C++ as a better version of C rather than its own separate language. – Martin York Feb 13 '14 at 00:50
-
@Masked You really gotta decide, if you want to have an answer for [tag:c] **or** [tag:c++]. There are fundamental differences (at least by consens)! – πάντα ῥεῖ Feb 13 '14 at 01:12
-
Don't see how this question really is a dupe for the referenced one (what's written in the answers there is just **crap** compared to what has been gotten here already!!). – πάντα ῥεῖ Feb 13 '14 at 02:16
-
Pointers really aren't that hard. The only real precautions you need to take are to take some time to understand them and getting a good memory debugging tool like Valgrind, and you'll be set. – Crowman Feb 13 '14 at 02:42
-
@PaulGriffiths - excellent advice "use a good memory debugging tool". – Floris Feb 13 '14 at 15:48
3 Answers
- Always initialize them
- Check the bounds (size of pointer offset / index)
free
the memory when done- Set to
NULL
after freeing - Check they are not
NULL
before accessing - When you malloc, use
thing = malloc(N * sizeof *thing)
- Don't overwrite a pointer that was
malloc
ed before youfree
it. - ...

- 45,857
- 6
- 70
- 122
-
1You should change the last one to "don't overwrite a pointer without freeing it first" – BWG Feb 13 '14 at 00:06
-
2
-
@DieterLücking - absolutely. It's the half of `"C/C++"` that I vaguely understand.... and the one that most needs people to be careful about pointers (since there are so many cool things in C++ that are missing in C. Hence the `++` I suppose). – Floris Feb 13 '14 at 00:12
-
1The answer covers the [tag:c] concerns all well, but doesn't cover [tag:c++] even partially ... – πάντα ῥεῖ Feb 13 '14 at 01:14
-
@pantarei - you are right; I focused on C because (a) I know it better and (b) it is more vulnerable, missing many of the protective C++ constructs you point out. – Floris Feb 13 '14 at 01:22
Some good advice there in the comments and Floris' answer, but IMO "Don't use pointers" isn't one of them
shared_ptrs are great to protect against leaks but you can't always use them. For example you are not supposed to use them with boost::intrusive containers.
additionally shared_ptrs wont help you if you have a container of said shared_ptrs and you just add but never remove from the container. You still "leak" the resources, though you haven't lost the ability to remove it.
other misc hints:
As with all resources I find it best to minimize the code-paths by which one type can be allocated & freed, so that I can match them up in review and/or instrumentation.
when allocating c-strings don't forget to reserve room for your terminator

- 5,774
- 3
- 30
- 44
-
1_'don't use pointers'_ is a really stupid, and too much narrowing advice!! – πάντα ῥεῖ Feb 13 '14 at 01:20
-
1@πάνταῥεῖ - I think nhed is saying: "of all the good advice given, 'don't use pointers' isn't one of them". And he goes on to elaborate on that position. So the two of you are in agreement although your comment makes it look like you think you disagree. – Floris Feb 13 '14 at 15:45
-
plus-one for "minimize code paths by which you allocate / free". Keeping those things organized is very helpful to limit the ways that bugs can creep in. If you really hide the mechanisms you find yourself in C++ land... – Floris Feb 13 '14 at 15:46
-
1@Floris It was meant as an agreement. As it stands that's a bit hard to get, yes. – πάντα ῥεῖ Feb 13 '14 at 16:15
-
@πάνταῥεῖ - OK thanks for the clarification! Question for you: how does one tag you in a reply when using mobile site? I don't get the autocomplete hint, and not sure if `@pantarei` will be correctly transliterated and mapped to πάνταῥεῖ by the notification service. Thoughts? See comment I made below my answer (written from phone). Wonder if you received that notification... – Floris Feb 13 '14 at 16:24
-
1@Floris I didn't get a notification, but read it timely. Usually I'm checking back to my own comments/answers after a short while. I don't like to use SO from my smartphone/tablet so much, may be mainly because it's much harder to copy something (which I'm using a lot for comments or answers). There are other drawbacks, e.g. writing code samples works a lot better for me, if I'm using my laptop or development machine. – πάντα ῥεῖ Feb 13 '14 at 16:52
-
1@πάνταῥεῖ it's true that it is hard to use the site on mobile; but sometimes it's all I have... Agree with all you said. – Floris Feb 13 '14 at 16:56
-
Yes, we were in violent agreement, sorry I havent been on SO all day. Also not sure how to edit and make that clearer. – nhed Feb 15 '14 at 00:03
Pointers are the core to programming languages like C and C++.
Not 'pointers' necessarily, let's talk about references ...
Note(!) that the role of 'pointers' has changed radically, when it comes to paradigms used in c vs. c++ (especially for c++11 language standards). So it would be difficult to handle them equally,
As for c++:
The usage of 'raw' c pointers is strongly discouraged with programming in c++, at least when these are to be allocated dynamically with new()
or new[]()
(which are the main point of being prone causing memory leaks, within your applications).
In c++ the use of reference (see &
and &&
operators), which aren't available for c, is preferred whenever possible (since they can't lead to such thing as a 'dangling reference' vs. a 'dangling pointer').
The principle introduced in c++ is named RAII, and manages lifetime of any class instances mainly from the call stack scopes of any functions and execution paths present (no matter, if these are called within the same thread or not). I'm not saying that can't be implemented using just plain c, but it's more difficult and error prone.
In a c++ application, the proper memory management for heap allocated class instances should be done using the smart pointer facilitiess of c++11, or at least the use of the good old (meanwhile deprecated) std::auto_ptr
class, for pre c++11 standards.
What are some precautions that must be taken while using pointers in C and C++?
There are some use cases for the usage of raw pointers in c++ of course (especially when interfacing between c and c++ APIs), but you should always test for their validity and know pretty good what you're actually doing! All the other cases are nicely covered by c++ standards, and you'll just need to use the right standard smart pointer class to get off from your problems.
-
-
@DieterLücking Is it? I'd **like** to improve it, because I see some differences of recommended handling of references in [tag:c] and [tag:c++] in general. Can you please elaborate which particular points to improve (for the [tag:c++] aspect, I've been mentioning in the beginning). – πάντα ῥεῖ Feb 13 '14 at 00:49
-
@DieterLücking ... Feel free to edit for improvement! (didn't manage to edit the comment above within the 5mins restriction) – πάντα ῥεῖ Feb 13 '14 at 00:57
-
@DieterLücking And as another point: **Confusion** of (tag:c and tag:c++) pointers and how to use them properly is ubiquitous (sorry I don't have a general answer for this point)! – πάντα ῥεῖ Feb 13 '14 at 01:26