- Is C++ a System Language?
- Memory Management Guidelines for malloc, calloc, realloc
- C++ 11 and Memory Management: Unique Pointers
- Conclusion
Memory Management Guidelines for malloc, calloc, realloc
The first guideline is to free memory only if that memory was allocated successfully. This rule sounds obvious, so let's see an example in Listing 4.
Listing 4Use free only when malloc succeeded.
char* textString = NULL; textString = malloc(256); if (textString == NULL) { cout<< "Failed malloc" << endl; return NULL; } // Use free() only if malloc() succeeded if (textString != NULL) { free(textString); textString = NULL; }
In Listing 4, we use free() only on an allocated block. Using free() on an unallocated block may result in unexpected behavior. This might be considered a system language detail; that is, the caller of free() is presumed to pass only valid (allocated memory) data. In other words, when you pass an item to free(), you must be sure that it is correct to do so.
Notice the way I set the value of textString to NULL both before allocation and after deallocation in Listing 4. Does this seem like a bit of a waste of time? The fact is, you'll often see this approach in legacy code. We'll see why I do this in the next section, where it will become apparent that when allocating memory we need to maintain state information.
Maintaining Memory Allocation State
Let's say you have code that allocates memory in a number of places. As we saw in Listing 4, when the time comes to deallocate that memory, it's best to know exactly which allocations succeeded and which ones failed. The goal is to avoid attempting to free unallocated memory.
A simple and effective approach to tackling this problem is to initialize all pointers to NULL before memory allocation and then to repeat the exercise just after deallocation. This way, you can be sure that all allocated variables contain an implicit indication of successful or unsuccessful allocation. This is a kind of overloading exercise, where a pointer variable contains information about whether or not it points at anything. If it doesn't point at anything, then it has the value NULL. On the other hand, if a pointer is not NULL, then it points at something valid and hence can be deallocated.
Imagine if, midway through code that allocates multiple blocks of memory, your code throws an exception. Without explicit NULL assignment as described here, it may be difficult to know which variables to free.
One obvious question: Can we live with code that leaks memory?
The Consequences of Memory Leaks
As mentioned earlier, if leaky code in a function or method repeats often enough, the system may eventually run out of physical memory. This is particularly likely on systems that run continuously. Also, even if virtual memory is available (which may not be the case on embedded systems), as physical memory runs low, new allocations may be made in virtual memory. However, you can be fairly certain that, if memory is leaking, some catastrophic failure will likely occur eventually. Memory leakage is therefore a problem best avoided by following some simple guidelines:
- Set unallocated pointers to NULL.
- Successful allocations with malloc, calloc, realloc should be paired with calls to free.
- Allocations with new should be paired with type-specific calls to delete; don't forget to use the array symbol if required.
- Set deallocated pointers to NULL.
- Ensure that programmer deallocation responsibilities are known in cases where a library returns allocated memory.
Sadly, there are also other possibilities for getting memory allocation wrong.
Off-by-One Memory Allocation
Aside from the issue of erroneously freeing unallocated memory, another common error can occur when allocating memory to hold a copy of a string. This error can occur as illustrated in Listing 5:
Listing 5No space is allocated for the string terminator.
char* srcStr = "Hello there"; char* textString = (char*)malloc(strlen(srcStr)); strncpy(textString, srcStr, strlen(srcStr)); // No room for string terminator
The string textString in Listing 5 is copied successfully from srcStr, but now it has no termination character.
In Listing 6, an additional space is allocated for the textString string. This design allows sufficient space to copy the incoming string. For completeness, I've added a few more items to Listing 6 based on the earlier guidelines about deallocation. See if you can figure out why I made the code changes.
Listing 6One additional space is allocated for the string terminator.
char* srcStr = "Hello there"; char* textString = NULL; textString = malloc(strlen(srcStr) + 1); if (textString != NULL) { memset(textString, '\0', strlen(srcStr) + 1); strncpy(textString, srcStr, strlen(srcStr)); // Lots more code here } if (textString != NULL) { free(textString); textString = NULL; }
In Listing 6, sufficient space is allocated for the string. In addition, the newly allocated string is zeroed out, followed by copying in the contents of the incoming string. Notice that I use the strncpy() function, which is safer than strcpy(). This is because strncpy()copies only a defined number of characters. The strcpy() function, on the other hand, copies up to the point where it finds a string-termination character. If you pass an unterminated string into strcpy(), it will copy beyond the end of the supplied incoming string until it finds a termination character. This might result in copying an arbitrarily large amount of memory[md]far beyond the size of the destination pointer.
What does C++ 11 offer when it comes to memory allocation? For one thing, it has what are called unique pointers. Before looking at C++ 11, let me make one important general point about memory leaks.
Memory-Leakage Avoidance Is the Best Cure
I recently had to chase down a memory leak in my own C++ code. The program was running out of memory after continuous operation for a day or so. It turned out that an array allocation wasn't being deleted correctly. The problem was basically as illustrated in Listing 7:
Listing 7Allocating and freeing an array in C++.
ComplicatedStruct* anArray = NULL; anArray = new ComplicatedStruct [5000]; //Lots of code here // Missing a call to delete []anArray; anArray = NULL;
In Listing 7, the allocated array is deleted after use, and its memory is returned to the free pool.
The preceding discussion on memory management has focused on legacy codebase issues. What about the use of so-called "smart pointers"? To answer this question, let's turn to C++ 11.