gpt4 book ai didi

c - 使用 realloc 连接字符串

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:16 25 4
gpt4 key购买 nike

我正在尝试连接两个字符串,假设“dest”字符串没有足够的空间来添加另一个字符串,所以我使用动态数组来解决它。

问题是在尝试编译代码时出现mremap_chunk错误。

我不知道我错过了什么,因为 realloc 调用中包含所有正确的参数。


错误:

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;
}

最佳答案

首先,您将非堆内存视为堆内存,不要那样做。

其次,您没有在计算中包括终止符的空间。

这里还有一些要点:

  1. 不要命名以 str 开头的函数,这是保留的命名空间。
  2. 缓冲区大小应为 size_t,而不是 int
  3. Don't cast the return value of malloc() in C .
  4. 当您知道大小时,使用 memcpy() 复制内存块。
  5. “右侧”字符串应该是 const
  6. 处理分配错误的可能性。
  7. 我认为按 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_t size_ab = a + b + 1;

s1 = realloc(s1, size_ab);

memcpy(s1 + a, s2, b + 1);

return s1;
}

关于c - 使用 realloc 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37989722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com