使用realloc连接字符串 [英] Using realloc to concat strings
本文介绍了使用realloc连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试合并两个字符串,假设目标"字符串没有足够的空间来添加另一个字符串,因此我正在使用动态数组来解决它.
I'm trying to concat two strings, supposing the "dest" string hasn't enough space to add another one, so I'm using dynamic arrays to solve it.
问题是尝试编译代码时出现的 mremap_chunk 错误.
The problem is a mremap_chunk error when trying to compile the code.
我不知道我要缺少什么,因为realloc调用中放置了所有正确的参数.
I don't know what I'm missing since the realloc call has all the right params place in.
错误:
malloc.c:2869: mremap_chunk: Assertion `((size + offset) & (GLRO (dl_pagesize) - 1)) == 0' failed.
Aborted (core dumped)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
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;
}
推荐答案
首先,您将非堆内存视为堆内存,请不要这样做.
First, you are treating non-heap memory as heap memory, don't do that.
第二,您没有在计算中包括终止符的空间.
Second you're not including space for the terminator in the calculation.
还有一些要点:
- 不要以
str
开头的名称功能,这是保留的名称空间. - 缓冲区大小应为
size_t
,而不是int
. - 不要转换
malloc()的返回值
在C 中. - 知道大小后,使用
memcpy()
复制内存块. - 右侧"字符串应为
const
. - 处理分配错误的可能性.
- 我认为按
sizeof(char)
(始终为1)进行缩放是一种不好的做法.
- Don't name functions starting with
str
, that's a reserved name space. - Buffer sizes should be
size_t
, notint
. - Don't cast the return value of
malloc()
in C. - Use
memcpy()
to copy blocks of memory when you know the size. - The "right hand side" strings should be
const
. - Deal with the possibility of allocation error.
- I consider it bad practice to scale by
sizeof (char)
, that's always 1.
假设相同的逻辑,这就是我的写法:
Here's how I would write it, assuming the same logic:
char * my_strcatt(char *s1, const char *s2)
{
const size_t a = strlen(s1);
const size_t b = strlen(s2);
const size_t size_ab = a + b + 1;
s1 = realloc(s1, size_ab);
memcpy(s1 + a, s2, b + 1);
return s1;
}
这篇关于使用realloc连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文