LoginSignup
0
0

More than 3 years have passed since last update.

手抜きアロケータ

Posted at

概要

PICやマイコンのプログラミングでmalloc使いたいけど使えない時に使っていたアロケータのソースです、ソースも短く開放の必要もなく簡単に使えますがチェック機構をなにも備えていないのでメモリの使用状況を把握していないとバグの原因になります。
1スコープ内で使い終わるように等気を使って使う必要があります。

ソース


#include <stdio.h>

char* myMalloc(size_t size) {
    static char buffer[8192];
    static int nextPosition = 0;
    int pos;
    pos = nextPosition;
    if ((pos + size) >= sizeof(buffer)) {
        pos = 0;
    }
    nextPosition = pos + size;
    return &buffer[pos];
}

int main(int argc, char** argv) {
    int i;
    char* p;
    for(i = 0; i < 10; i++) {
        p = myMalloc(16);
        sprintf(p, "i=%d\n", i);
        printf(p);
    }
    return 0;
}
// gcc main.c -o a.out

仕組み

確保した長さだけインデックスを進めて次の呼び出しではそのインデックスのアドレスを返します、サイズを超えるとインデックスは0に戻ります。
ソース見たほうが早いと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0