简体   繁体   中英

Segmentation fault with ulimit set correctly

I tried to help an OP on this question .

I found out that a code like the one below causes segmentation fault randomly even if the stack is set to 2000 Kbytes.

int main ()
{
   int a[510000];
   a[509999] = 1;
   printf("%d", a[509999]);
   return 0;
}

As you can see the array is 510000 x 4 bytes = 2040000 bytes.

The stack is set to 2000 Kbytes (2048000 bytes) using ulimit command:

  • ulimit -s 2000
  • ulimit -Ss 2000

Based on those numbers the application has room to store the array, but randomly it return segmentation fault.

Any ideas?

There's a few reasons why you can't do this. There are things that are already using parts of your stack.

main is not the first thing on your stack. There are functions called by the real entry point, dynamic linker, etc. that are before main and they are all probably using some of the stack.

Additionally, there can be things that are usually put on the top of the stack to set up execution. Many systems I know put all the strings in argv and all environment variables on top of the stack (which is why main is not the entry point, there's usually code that runs before main that sets up environment variables and argv for main).

And to top it off a part of the stack can be deliberately wasted to increase the randomness of ASLR if your system does that.

Run you program in the debugger, add a breakpoint at main, look up the value of the stack register and examine the memory above it (remember that most likely your stack grows down unless you're on a weird architecture). I bet you'll find lots of pointers and strings there. I just did this on a linux system and as I suspected all my environment variables were there.

The purpose of resource limits (ulimit) on Unix has never really been to micromanage things down to a byte/microsecond, they are there just to stop your program from going completely crazy and taking down the whole system with it. See them not as red lights and stop signs on a proper road, see them as run-off areas and crash barriers on a racetrack.

If you still wants to access the int location in the array, try to compile the code with out the main..this will not invoke _start

check this discussion enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM