これは私が初めて間違いをしていると申し訳ありません。文字列にヌルターミネーターがない場合はどうすればnullを返しますか
私はプールを割り当て、メモリに "Hello World"という文字配列を格納してからそれを取得するCプログラムを持っています。私のメインメソッドのコードの行の一つは、読み取ります
store(pool, 50, sizeof(str) - 1, str);
(私の店のメソッド変数は、(プール*プールされている私はこれを読んでいる場合はオフセット、int型のサイズ、void *型のオブジェクト)
をint型正しく割り当てられると、割り当てられるプールは文字列サイズよりも1小さいので、末尾にある\ 0を切り捨てます。
文字が最後になくなっていないことを確認してヌルを返します。
/* _POOL - pool
* int size - the size of the pool in bytes
* void* ipPool - pointer to memory malloc'd by the operating system
*/
typedef struct _POOL
{
int size;
void* memory;
} Pool;
/* Allocate a memory pool of size n bytes from system memory (i.e., via malloc())
* and return a pointer to the filled data Pool structure */
Pool* allocatePool(int n)
{
if(n <= 0)
{
return NULL;
}
Pool *pool = malloc(sizeof *pool);
if(!pool)
{
return NULL;
}
pool->size = n;
if(!(pool->memory = malloc(n)))
{
return NULL;
}
return pool;
};
/* Free a memory pool allocated through allocatePool(int) */
void freePool(Pool *pool)
{
if(!pool)
{
return;
}
if(pool->memory)
{
free(pool->memory);
}
free(pool);
};
/* Store an arbitrary object of size n bytes at
* location offset within the pool */
void store(Pool *pool, int offset, int size, void *object)
{
if(!pool)
{
return;
}
if(size + offset > pool->size)
{
return;
}
memcpy(pool + offset, object, size);
};
/* Retrieve an arbitrary object of size n bytes
* from a location offset within the pool */
void *retrieve(Pool *pool, int offset, int size)
{
if(!pool)
{
return NULL;
}
void *obj = malloc(size);
if(!obj)
{
return NULL;
}
if(size + offset > pool->size)
{
return NULL;
}
return memcpy(obj, pool + offset, size);
};
void main()
{
const int poolSize = 500;
Pool* pool;
int x = 5;
char c = 'c';
char str[] = "Hello World";
/* Should retrieve Hello World */
store(pool, 8, sizeof(str), str);
printf("Test 4: Store an arbitrary multi-byte value\n");
printf("\tStored: %s\n", str);
printf("\tRetrieves: %s\n", (char*)retrieve(pool, 8, sizeof(str)));
/* Should retrieve null */
store(pool, 50, sizeof(str) - 1, str);
printf("Test 5: Store an arbitrary multi-byte value with no null terminator\n");
printf("\tStored: %s\n", str);
printf("\tRetrieves: %s\n", (char*)retrieve(pool, 50, sizeof(str) - 1));
};
はすべて私が関係していると思うコードです。これは現在、Hello Worldに入れており、Hello Worldを取得しています。
メインメソッドのいずれも編集できません。関数と構造体の内容のみを編集できません。
ソースコードを表示する場合は、それが単純な自己完結型の例であることを確認してください。あなたの例は、署名のみを知っている関数を呼び出すonelinerです。どのようにメモリプールポイントを割り当てましたか? – TheBlastOne
'sizeof(str) - 1'は有用ではなく、' strlen(str)+ 1'より可能性が高い –
しかし末尾のヌル文字がないとstrlenは失敗します。 – TheBlastOne