473,386 Members | 1,598 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

VLA feature of C99 vs malloc

Suppose
int size = INT_MAX / 8;
char a[size];
are declared to use the feature of variable lenght array(VLA) in C99.
With appropriate #includes, when this code is run, segmentation fault
occurs in Red Hat enterprise Linux with 32-bit compiler.

Howver if
char * str = (char *)malloc(INT_MAX);
is declared and run , with appropriate headers, malloc is able to
return INT_MAX bytes.(this is 8 times more than the previous VLA
declaration)

Does this mean that malloc should be preferred over variable length
arrays, for huge memory allocations ?
Does the standard specify any limit regarding the size of VLA.

Dec 18 '06 #1
11 5059
Le 18-12-2006, subramanian <su**************@yahoo.coma écrit*:
Suppose
int size = INT_MAX / 8;
char a[size];
are declared to use the feature of variable lenght array(VLA) in C99.
With appropriate #includes, when this code is run, segmentation fault
occurs in Red Hat enterprise Linux with 32-bit compiler.

Howver if
char * str = (char *)malloc(INT_MAX);
is declared and run , with appropriate headers, malloc is able to
return INT_MAX bytes.(this is 8 times more than the previous VLA
declaration)

Does this mean that malloc should be preferred over variable length
arrays, for huge memory allocations ?
This limitation is platform-specific, and C99 does not states
so. But, in many platform, you can found this kind of limitations.
Does the standard specify any limit regarding the size of VLA.
Not to my knowledge.

Marc Boyer
Dec 18 '06 #2

On Mon, 18 Dec 2006, subramanian wrote:
Suppose
int size = INT_MAX / 8;
char a[size];
are declared to use the feature of variable lenght array(VLA) in C99.
With appropriate #includes, when this code is run, segmentation fault
occurs in Red Hat enterprise Linux with 32-bit compiler.

Howver if
char * str = (char *)malloc(INT_MAX);
is declared and run , with appropriate headers, malloc is able to
return INT_MAX bytes.(this is 8 times more than the previous VLA
declaration)

Does this mean that malloc should be preferred over variable length
arrays, for huge memory allocations ?
I think your problem has little to do with VLAs. Your problem is that you
allocate a large automatic object. Most likely replacing the VLA with a
normal automatic C array such as:

char a[INT_MAX/8];

will yield the same problem. In general automatic objects are allocated on
the stack, and platforms place various retrictions on the size of the
stacks. For example Windows places an upper limit of 1 megabyte, the
kernel-mode stack of linux is limited to 8 or 4 kilobytes. Moreover, some
system administrators place per-process limits on the stack size. Bottom
line: If you want to allocate large objects, use *alloc(), not automatic
local variables.

Emil

Does the standard specify any limit regarding the size of VLA.

Dec 18 '06 #3
On 18 Dec 2006 01:24:25 -0800, "subramanian"
<su**************@yahoo.comwrote in comp.lang.c:
Suppose
int size = INT_MAX / 8;
char a[size];
are declared to use the feature of variable lenght array(VLA) in C99.
With appropriate #includes, when this code is run, segmentation fault
occurs in Red Hat enterprise Linux with 32-bit compiler.

Howver if
char * str = (char *)malloc(INT_MAX);
is declared and run , with appropriate headers, malloc is able to
return INT_MAX bytes.(this is 8 times more than the previous VLA
declaration)

Does this mean that malloc should be preferred over variable length
arrays, for huge memory allocations ?
Does the standard specify any limit regarding the size of VLA.
VLAs are a useless and unsafe feature added by C99, unless you know
they are always going to be very small.

They are a bone thrown to those rabid users of non-standard extensions
like alloca(), who insist that their programs can't possibly survive
the overhead of true memory allocation.

Like the extensions it replaces, VLAs suffer from the same problem.
They are limited by the environment's bounds on the size of automatic
allocation.

To prove this to your self, replace the line defining size as an int
with a macro defining it to the same value. If the program fails with
the macro because you implementation does not allow you an automatic
allocation that large, it will fail with the VLA.

The only difference is that you can verify whether malloc() and its
relatives succeed or fail, but on many platforms allocating too large
a VLA results in immediate program termination.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Dec 18 '06 #4
Jack Klein a écrit :
VLAs are a useless and unsafe feature added by C99, unless you know
they are always going to be very small.
When you write
void fn(int m)
{
double tab[CONSTANT];
}

You do the same thing. All C users know by experience
that the allocations in the stack should be relatively
small.

The advantage with the C99 construct is that you allocate
exaclt what it is needed, not more, and not less. You *could*
allocate the same buffer with malloc obviously, but with
a lot more overhead.

jacob
Dec 18 '06 #5
2006-12-18 <qe********************************@4ax.com>,
Jack Klein wrote:
To prove this to your self, replace the line defining size as an int
with a macro defining it to the same value. If the program fails with
the macro because you implementation does not allow you an automatic
allocation that large, it will fail with the VLA.
You think the compiler can tell you at compile time that an automatic
allocation, even without being a VLA, will fail?
Dec 18 '06 #6

"jacob navia" <ja***@jacob.remcomp.frwrote in message
news:45***********************@news.orange.fr...
Jack Klein a écrit :
>VLAs are a useless and unsafe feature added by C99, unless you know
they are always going to be very small.

When you write
void fn(int m)
{
double tab[CONSTANT];
}

You do the same thing. All C users know by experience
that the allocations in the stack should be relatively
small.

The advantage with the C99 construct is that you allocate
exaclt what it is needed, not more, and not less. You *could*
allocate the same buffer with malloc obviously, but with
a lot more overhead.
I use salloc() in this case, the name is short for "stack allocate".

double stack[MAX];
double *stacktop;

void *salloc(int N)
{
double *answer = stacktop;
stacktop += (N + sizeof(double) -1)/sizeof(double);
return answer;
}

void sfree(void *ptr)
{
stacktop = ptr;
}

Very fast, and trivial to implement. You can easily add safety checks. The
only problem is that the local stack might not be in the cache, and memory
cannot be recycled for non-salloc() functions.
--
www.personal.leeds.ac.uk/~bgy1mm
freeware games to download.
Dec 18 '06 #7


On Mon, 18 Dec 2006, Jack Klein wrote:

<snipped>
VLAs are a useless and unsafe feature added by C99, unless you know
they are always going to be very small.

They are a bone thrown to those rabid users of non-standard extensions
like alloca(), who insist that their programs can't possibly survive
the overhead of true memory allocation.
Actually one good reason to using VLAs is that code using
multi-dimensional arrays (technically arrays of arrays) whose indices
depend on the function parameters is much more readable, than what can be
achieved using malloc() or the non-standard alloca(). But I agree, it's
way to easy to screw things up with stack overflows.

<snipped>
Emil

Dec 18 '06 #8


On Mon, 18 Dec 2006, Malcolm wrote:
>
"jacob navia" <ja***@jacob.remcomp.frwrote in message
news:45***********************@news.orange.fr...
>Jack Klein a écrit :
>>VLAs are a useless and unsafe feature added by C99, unless you know
they are always going to be very small.

I use salloc() in this case, the name is short for "stack allocate".

double stack[MAX];
double *stacktop;

void *salloc(int N)
{
double *answer = stacktop;
stacktop += (N + sizeof(double) -1)/sizeof(double);
return answer;
}

void sfree(void *ptr)
{
stacktop = ptr;
}

Very fast, and trivial to implement. You can easily add safety checks. The
only problem is that the local stack might not be in the cache, and memory
cannot be recycled for non-salloc() functions.
In addition to that your code is not reentrant. It won't work well in
multi-threaded environments. VLAs do.
Emil
--
www.personal.leeds.ac.uk/~bgy1mm
freeware games to download.
Dec 18 '06 #9
On Tue, 19 Dec 2006 01:09:59 +0200, Kohn Emil Dan wrote:
>
Actually one good reason to using VLAs is that code using
multi-dimensional arrays (technically arrays of arrays) whose indices
depend on the function parameters is much more readable, than what can be
achieved using malloc() or the non-standard alloca(). But I agree, it's
way to easy to screw things up with stack overflows.

<snipped>
Emil
I've never fiddled around much with anything other than malloc. I've always used
malloc for multi-dimensional arrays and to me, since it has been the only
way I've been doing it, it makes sense and I can read it fine; but now
that you mention it, it is probably a nightmare for anyone else to follow.

Dec 19 '06 #10
Jack Klein wrote:
On 18 Dec 2006 01:24:25 -0800, "subramanian"
<su**************@yahoo.comwrote in comp.lang.c:
Suppose
int size = INT_MAX / 8;
char a[size];
are declared to use the feature of variable lenght array(VLA) in C99.
With appropriate #includes, when this code is run, segmentation fault
occurs in Red Hat enterprise Linux with 32-bit compiler.

Howver if
char * str = (char *)malloc(INT_MAX);
is declared and run , with appropriate headers, malloc is able to
return INT_MAX bytes.(this is 8 times more than the previous VLA
declaration)

Does this mean that malloc should be preferred over variable length
arrays, for huge memory allocations ?
Does the standard specify any limit regarding the size of VLA.

VLAs are a useless and unsafe feature added by C99, unless you know
they are always going to be very small.

They are a bone thrown to those rabid users of non-standard extensions
like alloca(), who insist that their programs can't possibly survive
the overhead of true memory allocation.
Huh? So you've never measured the performance of malloc before? The
most useful malloc()'s I've ever seen (the ones with best long term
*sustained* performance) are around 50 clocks overhead per call.
Compare that to a stack pointer subtract -- which will cost at most 1
clock of real performance.

Now, I think C99 is full of it for other reasons, so my solution to
this is to commonly write alternative malloc()'s from scratch with all
sorts of functional differences (usually pool based with a "freeall"
function.) Straight C sucks for ADTs, if for no other reason, that the
cost of a malloc per atomic piece is huge. Going to pool based
allocators lets me bring the overhead down to just a few clocks (a
call, a couple of predicted ifs and adds ...) since the overhead of
"free" is amortized over all the atoms -- so this is an acceptable
stand in, but the C standard is of no help here.

In terms of a combination of speed and simplicity, being able to grab
dynamic memory from the stack is far more convenient. You don't need
to call free, so its like garbage collection without any of the
negative effects of it. (Though, it has new problems, like exposing
stack size considerations, as the OP has stepped into.)

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Dec 19 '06 #11
subramanian wrote:
Suppose
int size = INT_MAX / 8;
char a[size];
are declared to use the feature of variable lenght array(VLA) in C99.
With appropriate #includes, when this code is run, segmentation fault
occurs in Red Hat enterprise Linux with 32-bit compiler.

Howver if
char * str = (char *)malloc(INT_MAX);
is declared and run , with appropriate headers, malloc is able to
return INT_MAX bytes.(this is 8 times more than the previous VLA
declaration)

Does this mean that malloc should be preferred over variable length
arrays, for huge memory allocations ?
Does the standard specify any limit regarding the size of VLA.
cat f.h
#ifndef F_H
#define F_H
void f(int size);
#endif//F_H
cat f.c
#include "f.h"

void f(int size) {
char a[size];
a[0] = '0';
return;
}
cat main.c
#include <limits.h>
#include "f.h"

int main(int argc, char* argv[]) {
const int size = INT_MAX/8;
f(size);
return 0;
}
gcc -Wall -std=c99 -O2 -c f.c
gcc -Wall -std=c99 -O2 -o main main.c f.o
./main
Segmentation fault
limit stacksize
stacksize 10240 kbytes
limit stacksize unlimited
limit stacksize
stacksize unlimited
./main

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 19 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: john smith | last post by:
Can someone please explain to me what is happening when I do a malloc(0). This is what I did. int* p = (int*)malloc(0); Then I printed the value of p and of course it was non-null. But...
231
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought...
7
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ...
32
by: toolmaster | last post by:
Since many of the modern computer languages have built-in namespace features, I can't understand why not add this feature into standard C. I've heard many people complain of the lacking of...
15
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that...
68
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting;...
40
by: Why Tea | last post by:
What happens to the pointer below? SomeStruct *p; p = malloc(100*sizeof(SomeStruct)); /* without a cast */ return((void *)(p+1)); /* will the returned pointer point to the 2nd...
71
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a...
2
by: ssubbarayan | last post by:
Dear all, I am in the process of implementing pageup/pagedown feature in our consumer electronics project.The idea is to provide feature to the customers to that similar to viewing a single sms...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.