Sure - assuming that your stack is large enough to hold fileLen+1
items, you can do this:
unsigned char buffer[fileLen+1];
and skip the call to free()
at the end. This works, because C99 allows you to make arrays of variable size. In C++, however, this would not work *. Since most of your program is in C, however, you should be able to use the standard C construct by using a C99 standard-compliant compiler.
Note, however, that unlike malloc
that would return NULL
on failure, letting you handle the out of memory situation when the file is too large, this way of allocating memory in the automatic area (i.e. on the stack) will crash your program right away.
Also note that since the file is not a C string, you do not need fileLen+1
; fileLen
would be sufficient to fit the entire file.
* There are compilers that provide a C++ language extension to support variable-length arrays, but the resultant code would not be standard.