我對 C 有點陌生,我試圖制作一個類似 malloc 函式的東西,只是為了練習指標和所有這些東西。一切正常,但是當我洗掉printf主函式中的函式時,它回傳了 SIGBUG 錯誤。從我讀到的 SIGBUS 錯誤是當處理器嘗試讀取或寫入物理上不可用的記憶體時,我不知道這與洗掉 printf 函式有什么關系。我還在其他 C 和 C 編譯器上嘗試了相同的代碼,它作業得很好,沒有任何錯誤。
這是代碼:
#include <stdio.h>
#define heap_size 4096
#define m_availble 0x00
#define m_allocated 0x01
#define m_freed 0x02
typedef unsigned int uint;
char heap[heap_size]; //memory for Alloc function
void* Alloc(uint size);
void StoreInt(uint position, int value);
int GetInt(uint position);
void ShowHeap(uint position);
int main()
{
int* MyPtr = (int*)Alloc(sizeof(int) * 4);
MyPtr[0] = 69420;
//printf("myptr adr1: %p\n", &MyPtr[1]);
MyPtr[1] = 6;
//printf("myptr adr2: %p\n", &MyPtr[2]);
MyPtr[2] = 11;
ShowHeap(0);
}
void* Alloc(uint size) //allocates memory inside heap
{
uint position = 0;
size = sizeof(int) sizeof(char);
while(position size 40 < heap_size )
{
if(heap[position] == m_availble)
{
/*m_availble means it can store memory at this position*/
heap[position] = m_allocated;
/*m_allocated means memory at this is position
is allocated*/
StoreInt(position 1, size);
/*stores the size requied by user*/
return &heap[(position sizeof(int)
sizeof(char))];
/*returns pointer to adress that the user
can write to or read from*/
}
}
return NULL;
}
void StoreInt(uint position, int value)
{
/*stores valeu in to the heap*/
int* ptr = (int*)&heap[position];
ptr[0] = value;
}
int GetInt(uint position)
{
/*returns value from the heap*/
int* ptr = (int*)&heap[position];
return ptr[0];
}
void ShowHeap(uint position)
{
/*display adresses with values stored at those
adresses*/
printf("HEAP:\n");
for(int y = 0; y < 10; y )
{
printf("adr: %p - ", &heap[position
y * 4]);
for(int x = 0; x < 4; x )
{
printf("%i, ", heap[position 4 * y x]);
}
printf("\n");
}
}
uj5u.com熱心網友回復:
結盟
如果對齊不正確,以下是未定義的行為,可能會導致總線故障。
char heap[heap_size]; //memory for Alloc function
// StoreInt()
void StoreInt(uint position, int value) {
int* ptr = (int*)&heap[position];
ptr[0] = value;
// GetInt()
int* ptr = (int*)&heap[position];
return ptr[0];
替代方案,使用memcpy():
// StoreInt()
void StoreInt(uint position, int value) {
memcpy(&heap[position], &value, sizeof value);
// GetInt()
int x;
memcpy(&x, &heap[position], sizeof x);
return x;
我還在其他 C 和 C 編譯器上嘗試了相同的代碼,它運行得很好,沒有任何錯誤。
其他編譯器可能對int.
鑄件
鑄造是一股代碼味道。Cast 只是在 C 中偶爾需要。在 OP 的代碼中,所有的 casts 都有味道。
char可以簽
可能產出更多的資訊ShowHeap()就heap[]已經unsigned char比char。
真的想要負輸出 -128 到 127printf("%i, ", heap[position 4 * y x]);或 0 到 255?
uj5u.com熱心網友回復:
一個SIGBUS例外是常拋出總線對齊問題。malloc()記憶體管理的實作必須將回傳的指標對齊到可能的最大對齊方式,以使回傳的指標與任何型別的資料正確對齊。我過去遇到過這個問題,它會影響您使用指標的任何地方(printf當然也包括在內)。
實作記憶體分配器時要小心。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/356253.html
上一篇:C指標復制
下一篇:void函式不回傳任何內容-C
