2013-07-10 36 views
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; 
} 
+1

第一次縮進你的代碼 –

+0

請查看[你縮進的代碼和通知](http://stackoverflow.com/posts/17569539/revisions)其中@Kninnug推出標籤 –

回答

2

的問題是,您嘗試重新分配未分配的內存(在路上realloc首先想要它)。

您聲明str1作爲main函數中的數組,該內存將由編譯器在堆棧中分配,而不是在堆上分配。 realloc函數只能通過調用malloc,calloc或更早的realloc調用來重新分配堆中分配的內存。

而且如果realloc呼叫會工作,那麼你有內存泄漏,因爲你分配內存並將其分配給newstr1並在下一行覆蓋newstr1指針與newstr指針。

而你真的不應該分配一個固定的大小,請記住你將一個大小爲m的字符串附加到一個大小爲n的字符串。考慮一下如果m + n大於9會發生什麼情況。這會導致下一個問題,即由於您不復制終止的'\0'字符,因此不會終止結果字符串。

+0

優秀。你已經清除了我更多的懷疑,關於爲什麼當我使用malloc聲明str1時沒有錯誤。非常感謝您的回覆 – Akshit

0

試圖通過指針的指針,同時呼籲如下

strcatstring(str,&newstr); 
0

您正在使用可能不會結束str1用「\ 0」。您必須手動將該字符放在最後。

您無法重新分配堆棧上分配的內存。 str1被分配在堆棧上。

正確strcat()具有其他順序的參數。目標是第一位的。

您的命名約定很糟糕。 strnewstr?如何sourcedestination。而且,mn什麼也沒說。爲什麼不是sourceLendestinationLen

strcatstring()中完成循環之後,不要將'\ 0'字符放在末尾。你很可能會通過使用該字符串來獲得內存錯誤。

0

你的str1是一個數組,它在堆棧上分配。 realloc()必須用於其空間分配在堆上的指針。