开发者

Part of pthread stack seems to be already used

I'v开发者_如何学编程e set the stack size of a pthread in Linux to 16 KB. If I then push an array bigger than 8 KB on the stack, the applications stops with a segmentation fault. It seems to me that I am trying to access memory below the bottom of the stack, which is probably unmapped memory and hence the segfault.

Here is the sample code:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>

void *start_routine(void *arg)
{
  size_t size = 9*1024;
  unsigned char arr[size];

  memset(arr, 0, size);
}

int main()
{
  int err;
  pthread_attr_t threadAttr;
  size_t stacksize;
  void *stackAddr;
  pthread_t thread;

  pthread_attr_init(&threadAttr);
  pthread_attr_setstacksize(&threadAttr, 16*1024);
  pthread_attr_getstacksize(&threadAttr, &stacksize);
  printf("stacksize: %d\n", stacksize);

  pthread_create(&thread, &threadAttr, start_routine, NULL );
  pthread_join(thread, NULL);

  return 0;
}  

It seems strange that I loose around 8 KB of stack. I tried also with slightly bigger stack sizes. Somehow it seems to vary how much of the stack I can use.

I know that for nowadays-systems (except some embedded systems) these few bytes are not really important but I'm just curious why I cannot use most of the defined stack. I do not expect that I can use the whole stack, but loosing around 8 KB seems quite much.

What information is there put on the thread's stack before the entry-routine is called?

Thanks Philip


After some investigation in the glibc nptl source code I come to the conclusion that at the bottom of the stack there is put the pthread-struct of the thread who owns the stack and likely some other variables depending on the glibc-configuration. They use together around 3K. The top of the stack is filled with a guard page, which is typically 4K big. Thus around 7-8K are already used. I am a bit surprised that at least the memory for the guard page is not allocated separately. On the top of my head I thought to remember that that would be the case but it isn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜