我有一個任務,我需要使用緩沖區溢位登錄一個簡單的程式。該程式使用gets() 和strcpy() 將兩個args 放入v.username 和v.password。
struct {
int32_t goodcanary;
char password[25];
int32_t canary;
char good_username[25];
char good_password[25];
char username[25];
} v;
金絲雀是我知道的 10 位數字。由于 int32_t 只有 4 個位元組,我將數字轉換為 ascii 并希望溢位作為 input2 的密碼,并且由于金絲雀在記憶體中的密碼之后,我想我可以在它溢位后將它放在 input2 的末尾。我無法讓它作業,我知道結構有填充,但我不知道它是如何作業的以及填充在哪里。這是結構的每個成員的記憶體位置:

如何查看填充的位置以及如何知道金絲雀值的放置位置?
謝謝你。
uj5u.com熱心網友回復:
規則基本上如下:
- 在具有對齊要求的系統上,必須始終從偶數地址開始分配結構。出于這個原因,結構需要以尾隨填充位元組結束,這樣這樣的結構的陣列就不會使下一個陣列項錯位。
- 在對整數有 4 位元組對齊要求的計算機上,結構中具有此類要求的每個成員都必須從可被 4 整除的地址開始。
- 字符陣列沒有對齊要求,因此它們可以在任何地址分配。
您可以使用offsetof( stddef.h) 列印任何結構成員的位元組位置。例子:
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
typedef struct
{
int32_t goodcanary;
char password[25];
int32_t canary;
char good_username[25];
char good_password[25];
char username[25];
} v;
#define print_offset(x) printf("Offset %s: %zu\n", #x, offsetof(v,x))
int main (void)
{
printf("Size of struct: %zu\n", sizeof(v));
print_offset(goodcanary);
print_offset(password);
print_offset(canary);
print_offset(good_username);
print_offset(good_password);
print_offset(username);
return 0;
}
輸出(x86_64 計算機):
Size of struct: 112
Offset goodcanary: 0
Offset password: 4
Offset canary: 32
Offset good_username: 36
Offset good_password: 61
Offset username: 86
由于canary從 32 開始,因此必須插入 32-25-4=3 個填充位元組。并且它們必須是在 4 位元組對齊之后插入password的goodcanary,不需要尾隨填充。
或者,如果您愿意:
offsetof(v, canary) - sizeof((v){0}.password) - offsetof(v,password)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/488066.html
