【问题标题】:Error freeing memory after sorting the array pointer对数组指针进行排序后释放内存时出错
【发布时间】:2017-05-11 10:02:14
【问题描述】:

如何保持分配内存的位置,以便释放排序数组的内存不会受到影响?

我正在尝试对指针数组进行排序。我注意到当我释放 words 双指针变量时,它会给出错误 HEAP CORRUPTION DETECTED。我输入的输入是“f ff 1”。

未排序:f ff 1 排序:1 f ff

我注意到,当我对它进行排序和释放时,它会期望相同的顺序,即“f ff 1”。这就是为什么我得到了一些错误。

关于如何释放已排序指针数组的任何建议?

#include <stdio.h>

/*
    A logical type
 */
typedef enum {
    false,
    true,
} bool;

/*
    Bubble Sort
*/
void sort(char *myargv[], int n)
{
    int i, j, cmp;
    char tmp[256];

    if (n <= 1)
        return; // Already sorted

    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n-1; j++)
        {
            cmp = strcmp(myargv[j], myargv[j+1]);

            if (cmp > 0)
            {
                strcpy(tmp, myargv[j+1]);
                strcpy(myargv[j+1], myargv[j]);
                strcpy(myargv[j], tmp);
            }
        }
    }
}

void printArray(char *myargv[], int myargc)
{
    int i = 0;
        for (i = 0; i < myargc; ++i) {
            printf("myargc[%d]: %s\n",i , myargv[i]);
        }
}

int main (int argc, char *argv[])
{
    char text[256];
    char *myargv[256];
    char *myargvTemp[256];
    int myargc;
    int i = 0;
    int text_len;
    bool new_word = false;
    int index_start_word = 0;
    char **words;                                         //this will store the found word
    int count = 0;

    while(1){
        printf( "Enter text:\n");
        gets(text);                                       //get the input
        text_len = strlen(text);                          //get the length of the text
        words = (char **) malloc(text_len * sizeof(char));

        if (strlen(text) == 0 || text == '\0') exit(0);  //exit if text is empty


        for (i = 0; i < text_len ; ++i){
            if(text[i] != ' '){                          //if not space
                if(new_word == false){
                    new_word = true;
                    index_start_word = i;
                }
            } else {
                if (new_word == true) {
                    words[count] = (char *)malloc(i - index_start_word * sizeof(char)+1);   //memory allocation
                    strncpy(words[count], text + index_start_word, i - index_start_word);
                    words[count][i - index_start_word] = '\0';                              //place NULL after the word so no garbage
                    myargv[count] = words[count];
                    new_word = false;
                    count++;
                }

            }

            if (new_word == true && i == text_len-1){
                words[count] = (char *)malloc(i - index_start_word * sizeof(char)+2);
                strncpy(words[count], text + index_start_word, (i+1) - index_start_word);
                words[count][(i+1) - index_start_word] = '\0';
                myargv[count] = words[count];
                new_word = false;
                count++;
            }
        } 

        myargc = count;
        //not sorted
        printf("myargc is: %d\n", myargc);           
        printArray(myargv, myargc);

        //sorting happen
        sort(&myargv, myargc);
        printf("-----sorted-----\n");
        printf("myargc is: %d\n", myargc);
        printArray(myargv, myargc);

        memset(myargv, 0, 255);                         
        count = 0;
        i = 0; 


        //free the memory of words
        for (i=0; i<myargc; ++i) {
                free(words[i]);
        }
    }

    return 0;
}

【问题讨论】:

  • 添加#include &lt;string.h&gt;#include &lt;stdlib.h&gt;,打开编译器警告并阅读它们。
  • 我明白你的意思,我想它应该是 sort(myargv, myargc); .但是通过改变释放错误仍然存​​在。
  • 可能你没有为malloc分配足够的内存。检查您的写入内容是否超出了 malloc 返回的内存块。
  • 试试words = (char **) malloc(text_len * sizeof(char *))
  • 这是我见过的最奇怪的定义bool的方式。如果你可以使用C99或以上,你应该使用&lt;stdbool.h&gt;

标签: c arrays pointers memory-management


【解决方案1】:

您的代码中至少有 2 个问题:

  • 您没有为指针数组分配足够的空间:将words = (char **) malloc(text_len * sizeof(char)); 更改为:

    words = malloc(text_len * sizeof(char *));
    

    这种分配实际上是不正确的:您应该计算字数并为指针数组分配正确的大小,或者使用固定大小的数组。

  • 您交换字符串的内容而不是交换指针。这是不正确的,因为各种字符串的长度不同。

这里是排序函数的修正版本:

void sort(char *myargv[], int n) {
    int i, j, cmp;

    if (n <= 1)
        return; // Already sorted

    for (i = 0; i < n; i++) {
        for (j = 0; j < n-1; j++) {
            cmp = strcmp(myargv[j], myargv[j+1]);
            if (cmp > 0) {
                char *tmp = myargv[j+1];
                myargv[j+1] = myargv[j];
                myargv[j] = tmp;
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    你想让单词持有指向 char 的指针,所以你需要改变

     words = (char **) malloc(text_len * sizeof(char)); //will allocate array of single byte
    

     words = (char **) malloc(text_len * sizeof(char *));// will allocate array of pointers
    

    【讨论】:

    • 谢谢你,但我在释放内存时仍然出错
    猜你喜欢
    • 1970-01-01
    • 2014-05-16
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2023-02-01
    相关资源
    最近更新 更多