當我嘗試將 calloc 回傳的指標與 BY2PAGE 對齊時,這會導致段錯誤。有沒有辦法(或者甚至合法)修改指標,使其在分配后對齊?
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define BY2PG 0x1000
char * vm;
static int roundup(u_int n, int align) {
if(n % align == 0) ;
// is already aligned so
// no action required, else
// align it:
else n = (align - (n % align));
return n;
}
int main() {
vm = (char *) calloc(0x100000, sizeof(char));
vm = (char *) roundup((u_int)vm, BY2PG);
vm[0] = 5; // seg fault
}
uj5u.com熱心網友回復:
與其用脆弱的用戶代碼冒險實作和未定義的行為,不如使用:
#include <stdlib.h> // Since C11
void *aligned_alloc(size_t alignment, size_t size);
該
aligned_alloc函式為一個物件分配空間,該物件的對齊方式由對齊方式指定,大小由大小指定,...
OP 假設 1)(u_int)vm不會丟失重要資訊(我認為這是段錯誤源)2)調整后的整數int,轉換為,轉換回指標是有效的 3)calloc(large_value, 1)回傳非NULL @Lindydancer
。
甚至初始分配也是可疑的,calloc(0x100000, sizeof(char));因為不清楚0x1000在有問題之后有多少大小的塊可供使用roundup()。
uj5u.com熱心網友回復:
感謝@WeatherVane - 這個版本按我的預期作業
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define BY2PG 0x1000
char * vm;
static uintptr_t roundup(uintptr_t n, int align) {
if(n % align == 0) ;
// is already aligned so
// no action required, else
// align it:
else n = (align - (n % align));
return n;
}
int main() {
vm = (char *) calloc(0x100000, sizeof(char));
printf("x\n", vm);
vm = (char *) roundup((uintptr_t)vm, BY2PG);
printf("x\n", vm);
vm[0] = 5;
printf("%d\n", vm[0]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360377.html
