1

I want to increase the stack size of a thread created through pthread_create(). The way to go seems to be

int pthread_attr_setstack( pthread_attr_t *attr,
                           void *stackaddr,
                           size_t stacksize ); 

from pthread.h.

However, according to multiple online references,

The stackaddr shall be aligned appropriately to be used as a stack; for example, pthread_attr_setstack() may fail with [EINVAL] if ( stackaddr & 0x7) is not 0.

My question: could someone provide an example of how to perform the alignment? Is it (the alignment) platform or implementation dependent?

Thanks in advance

abeln
  • 3,749
  • 2
  • 22
  • 31

2 Answers2

13

Never use pthread_attr_setstack. It has a lot of fatal flaws, the worst of which is that it is impossible to ever free or reuse the stack after a thread has been created using it. (POSIX explicitly states that any attempt to do so results in undefined behavior.)

POSIX provides a much better function, pthread_attr_setstacksize which allows you to request the stack size you need, but leaves the implementation with the responsibility for allocating and deallocating the stack.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • Thanks for the categorical answer :) – abeln Mar 24 '11 at 16:37
  • No problem. :-) Another flaw I failed to mention is that there's no portable way of setting up guard pages with `pthread_attr_setstack`, so stack overflows will lead to memory corruption with likely-dangerous consequences rather than just `SIGSEGV`. – R.. GitHub STOP HELPING ICE Mar 24 '11 at 16:50
1

Look into posix_memalign().

It will allocate a memory block of the requested alignment and size.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131