-1
我可以使用一些幫助與我的程序, 我寫了一個程序,計算一個句子中的字符數,爲此我正在使用malloc()
函數,您可以請參閱我的代碼**ArrPtr=malloc
。釋放帶有免費功能的內存導致我的程序崩潰
我用這個來算字謎,完成它後,我想繼續我的計劃的第二部分,我希望與free(arrPtr);
和程序崩潰釋放內存的時候我沒有(它沒有崩潰使用免費選項)。
這裏是我的代碼,
void main()
{
char str[1001] = { 0 };
char temp[1001] = { 0 }, temp2;
char strB[1001] = { 0 };
int printf_i, counter, i, q, flag, j = 1, r = 0, m = 1, length = 0, root = 0, m1 = 0;
int max_analogy = 0, counter2 = 0, O, sum, sum2;
char **arrPtr;
int k = 0;
int **matrix;
printf("Please enter the sentence, and then press Enter:\n");
gets(str);
//bubble sort
strcpy_s(strB, 1001, str);
for (i = 0; i < strlen(strB); i = q + 2)
{
do
{
flag = 0;
for (q = i; strB[q + 1] != 32 && strB[q + 1] != 0; q++)
{
if (strB[q] > strB[q + 1])
{
// Swap
temp2 = strB[q];
strB[q] = strB[q + 1];
strB[q + 1] = temp2;
flag = 1;
}
}
} while (flag != 0);
}
counter = 1;
length = strlen(strB);
for (i = 0; strB[i] != 0; i++)
{
if (strB[i] == 32)
{
strB[i] = 0;
counter++;
}
}
arrPtr = (char*)malloc(sizeof(char)*counter);
arrPtr[0] = strB;
q = 1;
for (i = 0; i < length - 1; i++)
{
if (strB[i] == 0)
{
arrPtr[q] = &strB[i + 1];
q++;
}
}
counter2 = 0;
for (i = 0; i < counter; i++)
{
for (q = i + 1; q < counter; q++)
{
if (arrPtr[q] == 0 || arrPtr[i] == 0)
continue;
if (!strcmp(arrPtr[q], arrPtr[i]))
{
counter2++;
arrPtr[q] = 0;
}
}
if (max_analogy < counter2)
max_analogy = counter2;
counter2 = 0;
}
printf("The maximum number of anagram words in this sentence is %d.\n", max_analogy);
free(arrPtr);
}
你正在寫超過分配給'arrPtr'更多修復它。 – Rohan