今回はC言語です。
メモリとは
メモリというのは資源です。
記憶するための領域で、沢山あると沢山記憶ができます。
よくあるPCのメモリは一時的に記憶しておくための機構であり、
長期保存がしたければ、そういう機構に記憶を依頼しないといけません。
何を作ったか。
C言語のmallocとreallocをラップして自分には使いやすい構造にしてみました。
苦労話。
reallocのコードを書いているときmallocのコードをコピペしてはまって、メモリースマッシュをしてしまいました。
メモリースマッシュは破壊の予兆になるのでやめましょう。
lisence
copyright 2019 Yakitori.
MitLisence.
Code
MemoryAllocator.h
# pragma once
# include <stddef.h>
# include <stdbool.h>
typedef struct Memory_ {
void* Memory;
size_t ElementSize;
size_t Length;
} Memory;
Memory MemoryAllocate(size_t N, size_t SizeOfElement);
Memory MemoryReAllocate(Memory* Mem, size_t N);
bool MemoryFree(Memory*);
MemoryAllocator.c
# include <stdlib.h>
# include <memory.h>
# include "MemoryAllocator.h"
Memory MemoryAllocate(size_t N,size_t SizeOfElement ) {
Memory M = { NULL,0 ,0};
M.Memory = malloc(N*SizeOfElement);
if (M.Memory != NULL) {
memset(M.Memory, 0, N*SizeOfElement);
M.Length = N;
M.ElementSize = SizeOfElement;
}
return M;
}
Memory MemoryReAllocate(Memory* Mem,size_t N) {
void *p = realloc(Mem->Memory,N*Mem->ElementSize);
if (p != NULL) {
//if (p != Mem->Memory) { free(Mem->Memory); }//this is safe??
Mem->Memory = p;
Mem->Length = N;
}
return *Mem;
}
bool MemoryFree(Memory* In) {
free(In->Memory);
In->Memory = NULL;
In->Length = 0;
In->ElementSize = 0;
return true;
}
main.c
# include "MemoryAllocator.h"
//#include <crtdbg.h>//ms env only.
int main() {
//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF| _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF);
Memory M = MemoryAllocate(16 ,sizeof(int));
Memory B = MemoryReAllocate(&M, 32);
MemoryFree(&B);
//_CrtDumpMemoryLeaks();//ms only.
return 0;
}