我需要分配一個字符串數組。長度爲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已停止工作」。
爲什麼你將''test''作爲'int'參數傳遞? – icktoofay
'output [i] = encryptor(output [i-2],input [i]);'內存泄漏。除此之外,如何分配'encryptor'的返回值? –
這些行'output [0] = encryptor(first,input [0]);'(etc)* *代替了你的變量,所以它沒有使用'malloc'ed空間 – Dave