Array or Malloc

c

I'm using the following code in my application, and it's working fine. But I'm wondering if it's better to make it with malloc or to leave it as is?

function (int len)
{
char result [len] = some chars;
send result over network
}

Best Answer

The main difference is that VLAs (variable length arrays) provide no mechanism for detecting allocation failures.

If you declare

char result[len];

and len exceeds the amount of available stack space, your program's behavior is undefined. There is no language mechanism either for determining in advance whether the allocation will succeed, or for determining after the fact whether it succeeded.

On the other hand, if you write:

char *result = malloc(len);
if (result == NULL) {
    /* allocation failed, abort or take corrective action */
}

then you can handle failures gracefully, or at least guarantee that your program won't try to continue to execute after a failure.

(Well, mostly. On Linux systems, malloc() can allocate a chunk of address space even if there's no corresponding storage available; later attempts to use that space can invoke the OOM Killer. But checking for malloc() failure is still good practice.)

Another issue, on many systems, is that there's more space (possibly a lot more space) available for malloc() than for automatic objects like VLAs.

And as Philip's answer already mentioned, VLAs were added in C99 (Microsoft in particular doesn't support them).

And VLAs were made optional in C11. Probably most C11 compilers will support them, but you can't count on it.

Related Topic