Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic arrays in C without malloc?

Tags:

I've always wondered how I could get away with this:

int main(int argc, char **argv) {     printf("%p %s %d\n", &argv[1], argv[1], strlen(argv[1]));     char copy[strlen(argv[1]) + 1];     strcpy(copy, argv[1]);     printf("%p %s %d\n", &copy, copy, strlen(copy));     return 0; } 

The char array copy gets allocated anyway and the program runs fine, printing out the original and the copy. And Valgrind doesn’t complain about anything.

I thought dynamic arrays weren’t possible in C without malloc. Was I wrong?

like image 722
lt0511 Avatar asked Jul 11 '11 21:07

lt0511


People also ask

What can I use instead of malloc in C?

An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used for storing similar types of elements as the data type must be the same for all elements.

Is dynamic array possible in C?

Unlike other high-level languages (Python, JavaScript, etc) C doesn't have built-in dynamic arrays.

Can you free without malloc?

Actually you can use free without calling malloc , but only if the value you pass to free is a null pointer. So not useful if what you want is a pointer which might point to an allocated block, but might point to a local array.


2 Answers

This is a C99 feature and could be implemented on prior versions by the compiler.

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the brace-level is exited.

like image 152
Joe Avatar answered Sep 23 '22 03:09

Joe


Variable-length arrays originated as a GCC extension, but they were also adopted by C99.

They are still being allocated on the stack, so making them "huge" is considered bad style (and will likely break on you someday).

like image 29
Nemo Avatar answered Sep 20 '22 03:09

Nemo