使用realloc来连接字符串
我试图连接两个字符串,假设“dest”字符串没有足够的空间来添加另一个字符串,所以我使用动态数组来解决它。
尝试编译代码时出现问题是mremap_chunk错误。
我不知道我错过了什么,因为realloc调用有所有正确的参数。
错误:
malloc.c:2869: mremap_chunk: Assertion `((size + offset) & (GLRO (dl_pagesize) - 1)) == 0' failed. Aborted (core dumped)
#include #include #include char *strcatt(char *s1, char *s2) { int a = strlen(s1); int b = strlen(s2); int i, size_ab = a+b; s1 = (char *) realloc (s1, size_ab*sizeof(char)); for(i=0; i<b; i++) { s1[i+a]=s2[i]; } s1[size_ab]='\0'; return s1; } int main() { char s1[]="12345"; char s2[]="qwerty"; strcatt(s1,s2); printf("%s\n", s1); return 0; }
您不能重新分配或free
未通过调用malloc
分配的malloc
或不是NULL
。
来自第7.22.3.5节。 C11草案中的reallocfunction
realloc
函数解除分配ptr
指向的旧对象,并返回指向具有size
指定大小的新对象的指针。 新对象的内容应与解除分配之前的旧对象的内容相同,直到新旧大小中的较小者为止。 新对象中超出旧对象大小的任何字节都具有不确定的值。
所以, s1 = (char *) realloc (s1, size_ab*sizeof(char));
你的输入(自动数组)显然是错误的,永远不要这样做。
然后还有许多问题可以通过调试器的一些帮助来解决。
首先,您将非堆内存视为堆内存,不要这样做。
其次,你没有在计算中包括终结器的空间。
以下是一些要点:
- 不要命名以
str
开头的函数,这是一个保留的名称空间。 - 缓冲区大小应为
size_t
,而不是int
。 - 不要在C中
malloc()
的返回值 。 - 当您知道大小时,使用
memcpy()
复制内存块。 - “右手边”字符串应该是
const
。 - 处理分配错误的可能性。
- 我认为通过
sizeof (char)
进行扩展是不好的做法,总是1。
这是我如何写它,假设相同的逻辑:
char * my_strcatt(char *s1, const char *s2) { const size_t a = strlen(s1); const size_T b = strlen(s2); const size_ab = a + b + 1; s1 = realloc(s1, size_ab); memcpy(s1 + a, s2, b + 1); return s1; }
clang调试器给出了非常明确的错误描述:
malloc: error for object 0x7fff6fbb16d6: pointer being realloc'd was not allocated set a breakpoint in malloc_error_break to debug
两个数组都初始化为字符串文字。 此外,您的函数尝试通过重新分配来修改字符串文字,这是C标准的错误 ,因为您无法重新分配您尚未分配的内容,然后将第二个字符串文字的成员复制到“对象”中意图通过在字符串文字上滥用realloc()
来修改。
如果你动态定义了第三个字符串,你可以在其中总结两者的内容,代码就可以工作:
#include #include #include char *mystrcatt(char *s1, char *s2) { int a = strlen(s1); int b = strlen(s2); int i, size_ab = a+b; char *s3 = malloc (size_ab*sizeof(char)); //sizeof(char) is always 1 for(i=0; i
请注意,你没有在C中malloc()
。