question about dynamic memory allocation

  • Thread starter Fernando Barsoba
  • Start date
F

Fernando Barsoba

Hi all,

I have a simple question regarding dynamic memory allocation.. is there
a way to create a variable for which we don't know its size using the
'stack' instead of the 'heap'? For instance, I have the following:
> #define MESG_LENGTH 12
> unsigned char packet[sizeof(struct ip) + MESG_LENGTH];

But what if I don't know beforehand the size of MESG_LENGTH? Can I have
#define a variable taking its value from outside the code? for instance,
from a file or a parameter?

I know that for these situations one usually uses the 'heap' (malloc,
etc).. but I was wondering if there is a way to do it as asked... just
curiosity..

Thanks,

FBM
 
A

Alex Fraser

Fernando Barsoba said:
I have a simple question regarding dynamic memory allocation.. is there
a way to create a variable for which we don't know its size using the
'stack' instead of the 'heap'?

With a C99 compiler, you may use variable length arrays. OT: on many
systems, a function alloca() exists which can achieve a similar effect.

Alex
 
F

Fernando Barsoba

Alex said:
With a C99 compiler, you may use variable length arrays. OT: on many
systems, a function alloca() exists which can achieve a similar effect.

Alex

Is this good programming style? Any problems doing this?
 
J

Jordan Abel

Is this good programming style? Any problems doing this?

alloca() is never good programming style. There are many problems with
doing it - In particular, many historical implementations are quite
buggy and in particular cannot be safely called in the middle of an
argument list.
 
T

tedu

Fernando said:
Hi all,

I have a simple question regarding dynamic memory allocation.. is there
a way to create a variable for which we don't know its size using the
'stack' instead of the 'heap'? For instance, I have the following:
#define MESG_LENGTH 12
unsigned char packet[sizeof(struct ip) + MESG_LENGTH];

But what if I don't know beforehand the size of MESG_LENGTH? Can I have
#define a variable taking its value from outside the code? for instance,
from a file or a parameter?

#define MAX_MESG_LENGTH 1024
is the easiest way to go in many cases.
 
F

Fernando Barsoba

Alex said:
With a C99 compiler, you may use variable length arrays.

So, do you mean by variable length arrays that this is valid?

int size_array = sizeof(struct ip) + cnf->msg_length;
/* cnf->msg_length returns an 'int' */
unsigned char packet[size_array];

FBM
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top