我试图找到一种不使用realloc
来扩展字符串容量的方法。例如,这段代码之间的主要区别是什么?
void insert(char *dest, char *src, int pos){
char *temp = malloc(strlen(dest)+strlen(src)+1);
/*
malloc failure handling
*/
strcpy(temp,dest);
//rest of code
}
和:
void insert(char *dest, char *src, int pos){
char *temp =(char*)realloc(dest,strlen(dest)+strlen(src)+1);
/*
realloc failure handling
*/
dest = temp;
//rest of code
}
还是有更好的方法呢?
请注意,src
和dest
都是使用malloc
初始化的。
答案 0 :(得分:2)
malloc --> memcpy --> free
实际上是realloc
在概念上所做的,只是有些优化。
由于这个优化,这个问题
此代码之间的主要区别是什么
可以这样回答:在内存碎片方面,前者可以更快,更高效。
如何在不使用realloc()的情况下扩展字符串容量?
如果 VLA *(在C99之前(可能在C11之前,而不是在C11之前,而不是在C ++中)不可用) ,您知道输入和< / em> 此大小永远不会导致堆栈溢出,然后仅然后您可以这样做:
#include <stdio.h>
#include <string.h>
...
char s1[] = "123";
char s2[] = "456";
char s3[] = "789";
char s[strlen(s1) + strlen(s2) + strlen(s3) + 1];
strcpy(s, s1);
strcat(s, s2);
strcat(s, s3);
puts(s);
将会看到
123456789
总的来说,如果开始玩malloc()
,就没有理由不去找堂兄realloc()
。
答案 1 :(得分:1)
realloc
等同于
void *my_realloc(void *old_p, size_t new_size) {
void *new_p = malloc(new_size);
if (!new_p)
return NULL;
size_t old_size = ...;
if (old_size < new_size)
memcpy(new_p, old_p, old_size);
else
memcpy(new_p, old_p, new_size);
free(old_p);
return new_p;
}
除了realloc
可以扩展或缩小现有存储块之外。这样可以避免将字节从旧位置复制到新位置的情况。
这意味着realloc
至少与malloc
+ memcpy
+ free
一样快,但可能更多。
答案 2 :(得分:0)
主要区别在于,良好的realloc实现将进行优化,并在可能的情况下跳过副本。 (就像检查内存中是否有大量可用空间来扩大分配,但这取决于内存的管理方式。)
如果您不想编写某种内存管理来在运行时处理未定义长度的字符串,没有比重新分配更好的解决方案了。