Domanda

I read some more info about stack and heap memory. All the pros and cons in here: What and where are the stack and heap?

However i always have this question. Should i use stack or heap for my variable? Just now i have a struct which is ca 10kb in size.

  • I'm going to use it globally in the whole program
  • I know that max number of the necessary structs will be 1000. (totally 10MB)
  • Sometimes i'll use only one of them so the rest 999 is empty.
  • I'm not going to use any recurrence.
  • The program is going to run 24/7 on linux(raspberry Pi with 512MB RAM) and i'll access single struct in 5 seconds interval.

What do you advice? should i allocate it on stack or heap? Both of them have advantages and disadvantages

Thanks in advance.

È stato utile?

Soluzione

A 10Mbyte stack is not reasonable on a small computer like a Rasberry Pi is.

Typical stack frames on the call stack should be a few kilobytes (especially for recent software, which have many dozens functions of call depth, e.g. when using a toolkit like Qt or Gtk).

So I would suggest using the heap in your case.

BTW, once you malloc-ed a pointer, accessing it (on stack or on heap) is nearly equivalent (there is the cache, but if you access it often enough it will stay in L1 cache). And a typical malloc (or free) takes some dozens of microseconds. So for a thousand of such data, heap is not a big deal.

Of course, you'll want to be careful to avoid memory leaks (by free-ing appropriately the malloc-ed data). Perhaps use valgrind.

You might consider using Boehm's conservative garbage collector, then you'll code GC_MALLOC and GC_STRDUP instead of malloc and strdup and you won't bother free-ing data.

Altri suggerimenti

Allocating variables in the stack is easy and fast, but the disadvantage is that stack is limited, heap is slower but much bigger.

Also the values which are allocated in stack are deleted once you leave the scope, so it can be good for small local values like primitive variables but not good for variables which are big in size. Also if you allocate too much in the stack you might run out of stack but that is not the case with Heap

I'm going to use it globally in the whole program

That's not going to work on the stack, unless you pass the variable to every single function you call.

Pre-allocate it on the heap, especially since you know the max size.

It's really a no-brainer. Allocate it on the heap. The few cycles more it takes to malloc the space isn't even a consideration for something that is going to remain in place, be update every 5 seconds, and be accessed 24/7.

The slightly harder question is whether to have the pointer globally or pass it around through every function you call. From your description this seems like one of those cases where a global is justified.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top