0

別の文字列の後に文字列を追加する関数を作成しようとしています。次のエラーが表示されます。助けてください。 * glibc が検出されました./a.out: realloc(): 無効な古いサイズ: 0x00007fff7af0d450 * *

// The following code concatenates the orignal string into the another
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void strcatstring(char *str,char *newstr)
{
    int m=strlen(str);
    int n=strlen(newstr);

    newstr=(char *)realloc(newstr,10*sizeof(char));
    char *newstr1=(char *)malloc(10*sizeof(char));
    newstr1=newstr;

    while(*newstr!='\0')
    {
        ++newstr;
    }
    while(*str!='\0')
    {
        *newstr=*str;
        ++newstr;
        ++str;
    }

    printf("%s",newstr1);
}


int main()
{
    int n=6;char *str;char str1[10];
    str1[0]='y';
    str1[1]='u';

    str=(char *)malloc(n*sizeof(char));
    printf("\nEnter the string\n");
    scanf("%s",str);
    puts(str);
    strcatstring(str,str1);

    return 0;
}
4

4 に答える 4

2

問題は、そもそも (必要な方法で) 割り当てられていないメモリを再割り当てしようとすることですrealloc

str1関数で配列として宣言するとmain、このメモリはコンパイラによってヒープではなくスタックに割り当てられます。この関数は、または以前の呼び出しreallocによってヒープに割り当てられたメモリのみを再割り当てできます。malloccallocrealloc

そして、realloc呼び出しが機能した場合、メモリを割り当てて割り当て、次の行でポインタをポインタでnewstr1上書きすると、メモリリークが発生します。newstr1newstr

mまた、実際には固定サイズを割り当てるべきではありません。 size の文字列を size の文字列に追加することを覚えておいてくださいn。が 9 より大きい場合に何が起こるかを考えてみてくださいm + n。これは次の問題につながります。つまり、終了文字をコピーしないため、結果の文字列を終了しないということです'\0'

于 2013-07-10T11:33:56.330 に答える