malloc(…): Join strings
Learning goals
You should learn how to:
- Use
malloc(…)
to allocate buffers on the heap. - Write bug-resistant code that uses
malloc(…)
. - Debug common problems that occur when using dynamic memory.
Overview
In this assignment, you will create a few functions for manipulating strings. While these functions are operations that are genuinely useful in some contexts, the real purpose of this assignment is to give you some practice using dynamic memory, starting with something simple (copying a string to the heap) and moving up to something a little fancier (joining several strings with a separator string).
Dynamic memory (aka “heap memory”)
As we discussed in class, memory is organized in segments.
The stack segment is where local variables and arguments are stored. One limitation of the stack is that you have to know in advance how big any array, string, or object will be. If your code will take input from a file, a user, the network, or external code that you didn't write, then you can't predict how big things need to be. Another limitation is that when a function returns, all local variables and arguments are invalidated (i.e., become unavailable).
The heap segment lets you
specify exactly how many bytes you need. You use
the malloc(…)
function to allocate (reserve)
that space. You allocate a buffer (a bunch of bytes) into which you can
store a string, array, or any data you like. Your buffer says allocated until you explicitly
deallocate it by calling the free(…)
function.
Example: Make a string on the heap with the letters, "abc".
// Declare a variable abc_string, allocate a new buffer on the heap sufficient to
// store 4 char's, and initialize abc_string to the address of the newly allocated buffer.
char* abc_string = malloc(sizeof(*abc_string) * 4);
// Populate the new string (i.e., store letters in it).
abc_string[0] = 'a';
abc_string[1] = 'b';
abc_string[2] = 'c';
abc_string[3] = '