Как узнать размер стека?
Можно ли из проги на С++ узнать размер стека? Просто нужно реализовать рекурсивные вычисления, и узнать насколько глубоко может зайти рекурсивная функция.
Как узнать размер стека?
Re: Как узнать размер стека?
Re: Как узнать размер стека?
Если более точно, то около min(getrlimit(RLIMIT_STACK)+getrlimit(RLIMIT_DATA), getrlimit(RLIMIT_AS)).
Реально чуть меньше, т.к. часть памяти уже занята.
Re: Re: Как узнать размер стека?
Правда, для нитевого стека это всё не годится.
В этом случае можно поковырять как-нибудь так:
register unsigned long esp asm("esp");
И далее ковырять /proc/self/maps на предмет размера карты.
Правда, это не переносимо 🙁
Может кто-нибудь получше что предложит в этом случае .
Re: Re: Re: Как узнать размер стека?
Хотя вот для POSIX Threads есть pthread_attr_getstacksize/pthread_attr_setstacksize.
По-моему, эти pthread_attr_getstacksize/setstacksize возвращают не совсем то. Как узнать attr для треда?
Для библиотеки GNU C: #include <sys/resource.h>
Размер общей памяти, использованной текущим процессом под стек
находится в элементе long ru_isrss структуры rusage,
заполняемой ф-ей int getrusage(int who, struct rusage* res);
где who = RUSAGE_SELF
Мягкий/жесткий предел размера стека
находится в элементе rlim_t rlim_cur/rlim_max структуры rlimit,
заполняемой ф-ей int getrlimit(int what, struct rlimit* res);
где what = RLIMIT_STACK
Как узнать размер стека c
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only.
empty() function is used to check if the stack container is empty or not. Syntax :
Errors and Exceptions 1. Shows error if parameter is passed 2. Shows no exception throw guarantee.
Application : Given a stack of integers, find the sum of the all the integers.
Algorithm 1. Check if the stack is empty, if not add the top element to a variable initialised as 0, and pop the top element. 2. Repeat this step until the stack is empty. 3. Print the final value of the variable.
size() function is used to return the size of the stack container or the number of elements in the stack container. Syntax :
Errors and Exceptions 1. Shows error if a parameter is passed. 2. Shows no exception throw guarantee.
Application : Given a stack of integers, find the sum of the all the integers.
Algorithm 1. Check if the size of the stack is zero, if not add the top element to a variable initialised as 0, and pop the top element. 2. Repeat this step until the stack size becomes 0. 3. Print the final value of the variable.
Checking available stack size in C
I’m using MinGW with GCC 3.4.5 (mingw-special vista r3).
My C application uses a lot of stack so I was wondering is there any way I can tell programatically how much stack is remaining so I can cleanly handle the situation if I find that I’m about to run out.
If not what other ways would you work around the problem of potentially running out of stack space?
I’ve no idea what size of stack I’ll start with so would need to identify that programatically also.
9 Answers 9
The getrusage function gets you the current usage . (see man getrusage ).
The getrlimit in Linux would help fetching the stack size with the RLIMIT_STACK parameter.
Please give a look at man getrlimit . The same information could be fetched by ulimit -s or ulimit -a stack size row. Also have a look at setrlimit function which would allow to set the limits. But as the mentioned in the other answers if you need to adjust stack then probably you should re consider your design. If you want a big array why not take the memory from the heap ?
![]()
Taking the address of a local variable off the stack would work. Then in a more nested call you can subtract the address of another local to find the difference between them
If you code is multi-threaded then you need to deal with storing the top_of_stack variable on a per-thread basis.
check if your compiler supports stackavail()
Assuming you know the size of the full stack you could probably add some assembly code to read ESP.
If you read ESP and save it aside in the main function you can compare the current ESP to the ESP you have in main and see how much ESP has changed. That’ll give you an indication of how much stack you’re used.
This is a problem I have given up on. With a lot of hacking and (mostly) praying, you can get a solution that works at a given time on a given machine. But in general there seems to be no decent way to do this.
You will have to obtain the stack position and size from outside your program (on Linux you might get it from /proc/<pid>/maps ). In your program you must somehow test where you are at the stack. Using local variables is possible, but there is no real guarantee that they are actually on the stack. You can also try to get the value from the stack pointer register with some assembly.
So now you have the location of the stack, its size and the current position and you assume you know in which direction the stack grows. When are you going in stack-overflow mode? You better not do it close to the end because your estimation (i.e. address of local variable or value from stack pointer) is probably a bit too optimistic; it’s not uncommon to address memory beyond the stack pointer. Also, you have no clue about how much room on the stack any given function (and the functions it calls) need. So you’ll have to leave quite some room at the end.
I can only advice you not do get into this mess and try to avoid very deep recursion. You might also want to increase your stack size; on Windows you have to compile this into the executable, I believe.
Как узнать размер стека?
Buffer = «\x55» * (1040 — 124 — 95 — 4) = 841
NOPs = «\x90» * 124
Shellcode = «\xda\xca\xba\xe4\x11. \x5a\x22\xa2»
EIP = «\x66» * 4′
задача в том чтоб потом гдето посмотреть то что мне нужно.
я делал вот так: (gdb) x/2000xb $esp+550
и там вот так
0xffffd79a: 0x77 0xa4 0x3d 0xe8 0x7c 0x7b 0x3d 0x66
0xffffd7a2: 0x66 0x66 0x66 0x00 0x4c 0x53 0x5f 0x43
0ч66666666 эт окусок нагрузки
вот регистры
eax 0xffffd395 -11371
ecx 0xffffd1b0 -11856
edx 0xffffd1d4 -11820
ebx 0x56556fd4 1448439764
esp 0xffffd174 0xffffd174
ebp 0xffffd178 0xffffd178
esi 0xf7fc2000 -134471680
edi 0x0 0
eip 0x56555551 0x56555551