I debug the next code:
/* filename: sample.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check_authentication(char *password) {
int auth_flag = 0;
char password_buffer[16];
strcpy(password_buffer, password);
return auth_flag;
}
int main(int argc, char *argv[]) {
if(argc < 2) {
printf("Usage: %s <string>\n", argv[0]);
exit(0);
}
if(check_authentication(argv[1])) {
puts("Yay");
}
}
an examination of memory shows that
auth_flag
is located before password_buffer
in memory even if I swap them in definition step:
int check_authentication(char *password) {
char password_buffer[16];
int auth_flag = 0;
strcpy(password_buffer, password);
return auth_flag;
}
Let's gdb -q ./sample.out
:
break 11
run AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
(gdb) i r rsp rbp
rsp 0x7fffffffd980 0x7fffffffd980
rbp 0x7fffffffd9c0 0x7fffffffd9c0
(gdb) x/20xw $rsp
0x7fffffffd980: 0x00000009 0x00000000 0xffffdefe 0x00007fff
0x7fffffffd990: 0xffffd9f8 0x00007fff 0x00f0b5ff 0x00000000
0x7fffffffd9a0: 0x41414141 0x41414141 0x41414141 0x41414141
0x7fffffffd9b0: 0x41414141 0x41414141 0x41414141 0x41414141
0x7fffffffd9c0: 0x41414141 0x41414141 0x41414141 0x41414141
(gdb) x/x &auth_flag
0x7fffffffd99c: 0x00000000
(gdb) x/x &password_buffer
0x7fffffffd9a0: 0x41414141
So, why is that? The stack grows upward toward lower memory addresses and auth_flag
first defined in check_authentication
's stack frame must locate before password_buffer
, meaning have higher address.
User contributions licensed under CC BY-SA 3.0