Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, Seg Faults, and Memory Management

I'm moving from Java to C++ and have really enjoyed it. One thing I don't enjoy is not understanding memory at all because Java used to do that for me.

I've purchased a book : Memory as a Programming Concept in C and C++ - Frantisek Franek

Are there some good sites for me to go and learn interactively about C/C++ and memory use (tutorials, forums, user groups)?

like image 895
Stephano Avatar asked Feb 09 '10 19:02

Stephano


People also ask

Can out of memory cause segmentation fault?

Segmentation fault is an error caused by accessing invalid memory, e.g., accessing variable that has already been freed, writing to a read-only portion of memory, or accessing elements out of range of the array, etc.

What is meant by segmentation fault or memory fault in C?

A segmentation fault occurs when your program attempts to access an area of memory that it is not allowed to access. In other words, when your program tries to access memory that is beyond the limits that the operating system allocated for your program.

What is seg fault?

A segmentation fault (aka segfault) is a common condition that causes programs to crash; they are often associated with a file named core . Segfaults are caused by a program trying to read or write an illegal memory location.

How do you handle a segmentation fault?

It can be resolved by having a base condition to return from the recursive function. A pointer must point to valid memory before accessing it.


1 Answers

Memory management is nearly automatic in C++ (with a few caveats).

Most of the time don't dynamically allocate memory.
Use local variables (and normal member variables) and they will construct and destruct automatically.

When you do need pointers use a smart pointer.
Start with using boost::shared_pointer<T> instead of pointers.
This will get you on the correct path and stop accidently deleting memory at the wrong time and 90% of your code will release correctly (unfortunately cycles will cause a problem (in terms of leaks only) and you will need to design accordingly (but we have other smart pointers to deal with cycles weak_ptr))

My fundamental rule is that a class never contain a RAW pointer. Always use some form of standard container or a smart pointer. Using these; destructor calls become automatic.

Once you have the feeling start reading about the other smart pointers and when to use them:

Smart Pointers: Or who owns you baby?

like image 81
Martin York Avatar answered Sep 30 '22 00:09

Martin York