What is malloc doing in this code?

c, c++, malloc

Solution

`malloc` is a function that allocates a chunk of memory on the heap and returns a pointer to it. It's similar to the `new` operator in many languages. In this case, it's creating a block of memory that can survive for an arbitrary length of time and have an arbitrary size. That in itself is fairly in-depth stuff, which is somewhat difficult to explain and warrants a separate question.

The `num + 1` compensates for the null terminator on the end of strings. Strings often need to know how long they are, and the C tradition is to allocate room for an additional character on the end of the string, which will always be the special character `\0`. That allows functions that deal with the string to determine the size of the string automatically. For example, if you wanted to do something to every character of a string without knowing how long the string is, you could do something like this:

const char *ptr = str;
while (*ptr != '\0') {
    process(*ptr);
    ptr++;
}

Problem

Could you explain following code? ``` str = (char *) malloc (sizeof(char) * (num+1)); ``` - What is `malloc` doing here? - Why is `num + 1` used?

Original source