This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Strange memory allocation int a[atoi(argv[1])] ?!


chimi wrote:

> I've just heard that teachers from one of the university of technology say
> that:
> 
> int a[atoi(argv[1])];
> 
> is correct way to dynamic allocation... what is more it looks like x =
> a[999999]; works! o_O
> but I run memusage test-prog 1000000 and it doesn't call *alloc nor free at
> all, but works well...
> 
> in the other hand
> int a[32];
> doesn't allow to acces its 1000000 element (it's ok of course)
> 
> I wanted to know what gcc does with atoi(argv[2])? Does it only OS allocate
> so huge heap so it works?

This is not a question about gcc, it's a question about the C language,
so it's off topic for this list.  A better place would be the comp.std.c
newsgroup.

There are two different things going on here.

When you declare "char foo[n]" and n is a compile-time constant then you
get a standard array of characters allocated on the stack (assuming this
is in a function not a global file-level scope.)  There will be no call
to any allocate or free function, as that is how the stack works -- you
just decrease a pointer.  IF there was not enough memory remaining on
the stack then you generally get a runtime fault and the program aborts.

In traditional C the 'n' must be a compile-time constant.  If you try to
compile your atoi() example on a ANSI or C90 compiler, it will fail.  It
is only recently in C99 that the standard allows for a new type of
array, called variable length array (VLA) in which the 'n' can be
unknown at compile time, as in your example.  VLAs work just like
alloca(), i.e. the memory still comes from the stack and is invalidated
whenever the block goes out of scope.  Thus it's only valid for
allocations that are small and temporary.

It is debatable whether use of VLAs should really be called "the correct
way for dynamic allocation."  For one thing, it's a C99 feature and
there are many compilers out there that have not implemented parts or
any of C99, so it makes your code very much less portable.

Also there is the general argument of stack vs. heap allocation, and
there are many circumstances where it would be a very bad idea to try to
use a VLA in place of malloc().  Your teachers should go over all of
this.

Brian


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]