Kamui Shirow said:
I will write a snippet to illustrate my doubt:
snippet 1:
void foo( int l )
{
char* tmp;
tmp = (char*) malloc( l * sizeof( char ) );
// DO SOMETHING
free( tmp );
}
snippet 2:
void foo( int l )
{
char tmp[l];
// DO SOMETHING
}
What is the difference in advantage if I use snippet 1 or 2?
Snippet 2 relies on Variable Length Arrays (VLA), which are part
of C99 but not part of C89. I have not used VLA myself, but reading
some of the other postings here, it sounds as if there are a noticable
number of compilers which either do not accept VLA at all or else
implement them differently than the C99 standard; in particular, I
believe people have said that gcc does something with VLA than
the C99 standard.
I have not looked at VLA, so I do not know what the largest
permitted array is.
Snippet 1 has a useless cast -- you do not need the (char *)
before the malloc(). That won't stop it from operating, that's
just not good style. Snippet 1 will work on C89 whereas Snippet 2 will
not work on C89. Snippet 1 has all the usual problems of malloc():
Depending on how the malloc() is implemented, malloc() can sometimes
be slow, or can sometimes not be able to find enough consequative
available memory even though there is enough available memory if you
could merge the seperate pieces of available memory together
("memory fragmentation"). And you've fallen into the classic pattern
in using malloc(), in that you failed to check to see whether
the system was able to give you the memory before you go ahead
and use it. Oh yes, and sizeof(char) is *defined* to be 1 so
there is no point in having the * sizeof(char) in the malloc().
Both snippets have the problem that you do not check that the variable l
is greater than 0 before you attempt to allocate space. Both would
fail for foo(-1).
You should also consider whether an "int" is large enough to
express the amount of space that might be desired. That's going
to depend on the context. It is legal in C implementations for
the largest int to be merely 32767 so if you were planning to
make foo available for a context in which someone might want
to allocate (say) 50000 bytes, then you should change the
user interface from specifying the size as an int . You could
change the size to long or (not in pure C89) long long, but
the most appropriate type for such a parameter is probably size_t .