这是我第一次在这里发布信息,对不起,如果我做错了什么。
我有一个C程序,该程序分配一个池,然后在内存中存储一个字符数组“ Hello World”,然后对其进行检索。我的main方法中的代码行之一如下:
store(pool, 50, sizeof(str) - 1, str);
(我的存储方法变量是(Pool * pool,int offset,int size,void * object)
如果我正确地阅读了此内容,则所分配的池比字符串大小小1,因此将\ 0减少到最后。
如何检查字符是否结尾丢失并因此返回null?
/* _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。
我不能编辑任何主要方法,只能编辑函数和结构的内容。
最佳答案
如果删除了结尾的空字符,则将删除唯一编码字符串长度的信息。无法查询分配的块的大小。
这是因为终止零是C编码字符串长度的方法。其他语言的运行时使用不同的方法,例如将字符串长度(作为字节或单词)存储在字符串引用变量(例如,Delphi)所指向的第一个字节中。
因此,无法检测到尾随null是否丢失。如果在那里,您可以搜索它。如果不存在,您的搜索将不可避免地访问字符串最后一个字节后面的内存位置,并且将无法正常工作。
而且由于搜索(或扫描)空字符正是strlen
的工作,因此您当然不能使用strlen
。
关于c - 如果我的字符串没有空终止符,如何返回空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36227398/