2013-04-14 18 views
0

我需要分配一個字符串數組。長度爲100,每個單元格可以包含100個字符的字符串大小。當我釋放一個字符串數組我的程序崩潰

typedef char* (*Encryptor3)(char*, char); 
char** encryptToString(char** input,int length,int first,Encryptor3 encryptor) 
{ 
int i=0; 
char** output=(char **)malloc(sizeof(char*)*length); 
for(i=0;i<length;i++){ 
    output[i]=(char *)malloc(sizeof(char)*(100+1)); 
} 
output[0]=encryptor(first,input[0]); 
output[1]=encryptor(first,input[1]); 

for(i=2; i<length ; i++) 
{ 
    output[i]=encryptor(output[i-2],input[i]); 
} 
return output; 
} 

int main() 
{ 
    char plain[] = {'p','l','a','i','n','t','e','x','t'}; 
    char** outputS = encryptToString(plain, 9, "test", idenString); 
    int i; 
    for(i=0; i<9; i++) 
     printf("%s\n", outputS[i]); 
    for(i=0; i<9; i++) //deallocating my array of strings 
     free(outputS[i]); 
    free(outputS); 
    return 0; 
} 

行「free(outputS [i]);」會崩潰的程序,我會得到一個普通的錯誤,說「myp.exe已停止工作」。

+0

爲什麼你將''test''作爲'int'參數傳遞? – icktoofay

+0

'output [i] = encryptor(output [i-2],input [i]);'內存泄漏。除此之外,如何分配'encryptor'的返回值? –

+4

這些行'output [0] = encryptor(first,input [0]);'(etc)* *代替了你的變量,所以它沒有使用'malloc'ed空間 – Dave

回答

1

而不是

output[...]=encryptor(...); 

做:

strcpy(output[...], encryptor(...)); 

這是假設由encryptor()使用的緩衝區是靜態的。

還要確保encryptor()返回的字符串不大於你分配給output引用的指針,即100個字符,不包括尾隨的零終止。

+0

我沒有除了這個好回答!它現在就像一個魅力 你甚至注意到我做錯了其他事情。 謝謝! (將第一個變量從int更改爲char *並將其從輸出[...] = encryptor(...);更改爲strcpy(output [...],encryptor(...));) –

+0

@ A'merMograbi :正如你似乎覺得答案很有用,你可以自由地接受它(通過點擊它的感嘆號),如果你喜歡它,你也可以upvote它... ;-) – alk

相關問題