2017-05-25 97 views
-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); 
} 
+0

你正在写超过分配给'arrPtr'更多修复它。 – Rohan

回答

1
arrPtr = (char*)malloc(sizeof(char)*counter); 

是错误的FO许多原因:

  1. arrPtr(char **)。使用C编译器进行强制转换是无用而且危险的。
  2. 必须分配sizeof(char *)

原因3是你的真正原因问题:当你写counter*sizeof(char *)(最有可能counter*8)你分配counter字节,所以你写出来的分配内存破坏malloc界内存池。


可以使用

arrPtr = malloc(sizeof(char *)*counter); 
相关问题