使用realloc连接字符串

时间:2016-06-23 11:01:00

标签: c arrays realloc strcat

我正在尝试连接两个字符串,假设“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;
}

3 个答案:

答案 0 :(得分:3)

您无法reallocfree未通过mallocNULL来电分配的内存。

7.22.3.5开始。 C11草案中的realloc函数

  

realloc函数释放ptr指向的旧对象   返回指向由size指定的size的新对象的指针。   新对象的内容应与旧对象的内容相同   在释放之前的对象,直到新旧的较小者   大小。新对象中的任何字节超出旧对象的大小   有不确定的价值观。

所以,s1 = (char *) realloc (s1, size_ab*sizeof(char));对你的输入(自动数组)来说显然是错误的,从来没有这样做。

然后还有更多问题可以通过调试器的帮助解决。

答案 1 :(得分:2)

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

其次,你没有在计算中包括终结者的空间。

以下是一些要点:

  1. 不要以str开头的函数命名,这是一个保留的名称空间。
  2. 缓冲区大小应为size_t,而不是int
  3. Don't cast the return value of malloc() in C
  4. 当您知道尺寸时,使用memcpy()复制内存块。
  5. &#34;右手边&#34;字符串应为const
  6. 处理分配错误的可能性。
  7. 我认为按sizeof (char)进行扩展是不好的做法,它始终为1。
  8. 这里是我如何编写它,假设相同的逻辑:

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

答案 2 :(得分:1)

clang 调试器提供了非常明确的错误描述:

malloc:  error for object 0x7fff6fbb16d6: pointer being realloc'd was not allocated
 set a breakpoint in malloc_error_break to debug

您的两个数组都被初始化为字符串文字。此外,您的函数尝试通过重新分配来修改字符串文字,这是C标准的wrong,因为您无法重新分配您尚未分配的内容,然后将第二个字符串文字的成员复制到您打算通过在字符串文字上滥用realloc()来修改“对象”。

如果你有动态定义了第三个字符串,你可以在其中总结两者的内容,代码就可以了:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

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<a; i++) { //inefficient
        (s3[i])=s1[i];
    }    

    for(i=0; i<b; i++) { //inefficient
        (s3[i+a])=s2[i];
    }

    s3[size_ab]='\0';

    return s3;
}


int main()
{
    char s1[]="12345";
    char s2[]="qwerty";
    char *s3 = mystrcatt(s1,s2);    
    printf("%s\n", s3);
    free(s3);
    return 0;
}

请注意,您don't cast 已在{。

中返回malloc()
相关问题