realloc函数错误:未分配指针realloc'd

时间:2015-10-10 00:40:45

标签: c

我试图在实现字符串组合函数时使用realloc函数。这个函数将合并两个字符串,leftPiece和rightPiece,左片的尾部和右片的头部重叠有数字num_overlap的字符。因为输入字符串的大小合适,我必须重新分配字符串,以便我有足够的空间来连接两个字符串。我的功能如下:

char* merge_overlap (char** leftPiece, char** rightPiece, int num_overlap) {
      printf("in merge_overlap, left is %s, right is %s \n", *leftPiece, *rightPiece);

    *leftPiece = (char*) realloc(*leftPiece, (strlen(*leftPiece) + strlen(*rightPiece) - abs(num_overlap) + 1) * sizeof(char) );
    *leftPiece = strcat(*leftPiece, *rightPiece + abs(num_overlap));
    return *leftPiece;
}

在这个函数中我首先重新分配左边的空间,然后连接两个字符串。但是当我编译时,我遇到了错误:

malloc: *对象0x100000f25的错误:未分配重新分配的指针 * 在malloc_error_break中设置断点以进行调试

任何人都可以看到这个问题是什么吗?

新增内容: 实际上,原始字符串数组在传入此函数之前已重新排列。字符串数组包含许多字符串,我首先试图找出两个重叠子字符串的字符串。然后我重新排列了两个字符串的索引,以便左边的部分总是具有较低的索引。代码如下:char * temp = frags [j];                         frags [j] = frags [i];                         frags [i] = temp;这可能会导致错误发生。

问题解决了: 代码改编如下:

char *result = malloc(strlen(*leftPiece) + strlen(*rightPiece) -abs(num_overlap) + 1);
        strcpy(result, *leftPiece);
        strcat(result, *rightPiece + abs(num_overlap));
        return result;

2 个答案:

答案 0 :(得分:0)

问题是,merge_overlap()要求您传入最初leftPiece编辑的malloc(),但您传入了另一种char *。< / p>

  

您只能realloc最初使用malloc分配的字符串。

要解决问题,您需要malloc()原始leftPiece

答案 1 :(得分:0)

正如J. Leffler和其他人指出的那样,你的错误在你以前的代码中,很可能leftPiece之前没有被声明为兼容指针,并且考虑到你的函数的工作,而不是之前分配的函数malloc(或类似)。为了realloc,指针不得静态声明。否则,您的功能正常:

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

char* merge_overlap (char** leftPiece, char** rightPiece, int num_overlap) 
{
    *leftPiece = realloc (*leftPiece, 
                        (strlen (*leftPiece) + 
                        strlen (*rightPiece) - 
                        abs(num_overlap) + 1));
    *leftPiece = strcat (*leftPiece, *rightPiece + abs(num_overlap));

    return *leftPiece;
}

int main (void) {

    char *str1 = strdup ("A quick brown fox jumps");
    char *str2 = strdup ("jumps over the lazy dog.");

    printf ("\n str1 : %s\n"
            " str2 : %s\n", str1, str2);

    merge_overlap (&str1, &str2, 5);

    printf ("\n merged:\n\n"
            " str1 : %s\n\n", str1);

    return 0;
}

<强>输出

$ ./bin/mergoverlap

 str1 : A quick brown fox jumps
 str2 : jumps over the lazy dog.

 merged:

 str1 : A quick brown fox jumps over the lazy dog.