1

Consider I have the following structure:

struct BigStruct {
  char data1[999];
  char data2[999];
  ...
  char dataN[999];
}

and somewhere in the code I have a non-static variable of the type with initialization:

struct BigStruct foo = 
{
 .data1 = {0},
 .data2 = {0},
 ...
 .dataN = {0},
}

Looks like here will be an attempt to allocate several KB of memory on the stack. Am I right?

Is it ok, or it's a kind of bad practice?

OhmSpectator
  • 127
  • 7
  • 1
    The stack does have a maximum size, so if you put too much stuff on it you'll have problems (`stackover`, ring a bell?). Check with your compiler what the max stack size is. – AntonH May 05 '14 at 12:08
  • The code will work but its bad practice(efficiency will be greatly reduced) to make structures very big. – akp May 05 '14 at 12:11
  • 1
    It depends. The problem with "the stack" is that it isn't introspectable by a C program, and it's impossible to tell from within your program whether you're using it correctly. There are clear benefits to automatic storage, but it's your responsibility to stay within the limitations of the platform. – Kerrek SB May 05 '14 at 12:11
  • If you try to allocate size greater than allowed one, compiler will throw out warnings. Atleast gcc does – coder hacker May 05 '14 at 12:13

2 Answers2

0

There's nothing wrong with using automatic storage.

If the structure is too large for your platform, your program might crash.

On a Linux system, you can look what the maximum stack size is, with ulimit -s or ulimit -a

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
0

It depends on your software architecture and your target.

If you are writing kernel code you don't want to use a lot of stack space; Linux kernel stacks are small.

User programs often have a 1 Mb or larger stack, so unless you have a lot of recursive routines, allocating a couple of kB on the stack usually isn't a problem.

In Linux, you can check the stack size with ulimit -s. The result is in KiB.

Community
  • 1
  • 1
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82