I'm trying to write an array to the stack in x86 assembly using the AT&T (GAS) syntax. I have ran into an issue whereby I can write ~8.37 million entries to the stack, and then I get a Segmentation fault
if I try to write any more. I don't know why this is, here's the code I'm using:
mov %rsp, %rbp
mov $8378658, %rdx
writeDataLoop:
sub %rdx, %rbp
movb $0b1, (%rbp)
add %rdx, %rbp
sub $1, %rdx
cmp $0, %rdx
jg writeDataLoop
Another odd thing that I've found is that the limit at which I can write data up to changes very slightly with each run (it's roughly at 8378658, which is also nothing significant in hex (0x7fd922). Can anyone tell me how to write more data to the stack, and also potentially explain what this arbitrary stack write limit is? Thanks.
To start off with, the default stack size is 8MB, this is the stack limit I was reaching. This can be found with the ulimit -a
command. However, one should not use the stack for large amounts of data (usually arrays). Instead, the .space
directive should be used, which, using AT&T syntax, takes the amount of data to store in bytes: .space <buffersize>
. This can be labelled, for example:
buffer: .space 1024
This allocates 1024 bytes of storage to the label buffer
. This label should be in the .bss
section of your program, allowing for read and write access.
Finally, to access this data (read or write), one can use buffer(%rax)
, where rax
is the offset.
Edit:
Using the .bss
section is more efficient file-size wise than using the .data
section, you just have to manually initialize the array.