I\'m a total C newbie, I come from C#. I\'ve been learning about memory management and the malloc()
function. I\'ve also came across this code:
char
Well, for a start, sizeof(char)
is always 1, so you could just malloc(3)
.
What you're allocating there is enough space for three characters. But keep in mind you need one for a null terminator for C strings.
What you tend to find is things like:
#define NAME_SZ 30
: : :
char *name = malloc (NAME_SZ+1);
to get enough storage for a name and terminator character (keeping in mind that the string "xyzzy" is stored in memory as:
+---+---+---+---+---+----+
| x | y | z | z | y | \0 |
+---+---+---+---+---+----+
Sometimes with non-char based arrays, you'll see:
int *intArray = malloc (sizeof (int) * 22);
which will allocate enough space for 22 integers.