【发布时间】:2017-11-08 07:17:44
【问题描述】:
我对以下功能有疑问。
当我尝试realloc() 记忆时,我得到的比我实际要求的要多!
在这种情况下,我尝试连接 2 个字符串,一个是 14 个字符长,一个是 11 个字符长,但最终结果是 memTemp 是 38 个字符长,即使 memNewSize 显示它在事实 25,有人知道该怎么做吗?
int dstring_concatenate(DString* destination, DString source)
{
assert(destination != NULL); // Precondition: destination ar ej NULL
assert(*destination != NULL); // Precondition: *destination ar ej NULL
assert(source != NULL); // Precondition: source ar ej NULL
//Dstring looks like this = "typedef char* Dstring;"
int memNewSize = strlen(*destination) + strlen(source);
char *memTemp;
memTemp = (char*)realloc(memTemp, sizeof(char) * memNewSize);
printf("%d\n", memNewSize);
printf("%d\n", strlen(memTemp));
if(memTemp == NULL)
{
printf("Could not allocate new memory.\n");
return 0;
}
else
{
*destination = memTemp;
strcat(*destination, source);
return 1;
}
}
【问题讨论】:
-
当然标题应该是“realloc allocates too much memory”
-
那为什么不编辑呢?
-
什么是
DString? -
不应该是
memNewSize + 1包含字符串终止符吗? -
至于你的问题,将
*destination传递给realloc调用不是更有意义吗?
标签: c pointers dynamic-memory-allocation realloc