c - 对数组指针排序后释放内存时出错

标签 c arrays pointers memory-management

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

我正在尝试对指针数组进行排序。我注意到,当我释放 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;
}

最佳答案

您的代码中至少有 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;
            }
        }
    }
}

关于c - 对数组指针排序后释放内存时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43912298/

相关文章:

c - 清理代码的最佳命令行工具是什么?

c - 从 C 函数返回指向 uint8_t 数组的指针 - 出现编译器错误

Java 数组中的 NullPointerException

c - 从 C 函数返回局部变量

c - 我刚刚读了指针和数组地址算术。但我已经搞混了

c++ - 等号是否在 char * 中重新分配内存?

c - 从指针打印?

php - 从表单发布数组

javascript - 当变量选择数组中的元素时,为什么 Node 看不到该元素?

c++14 unique_ptr 并使 unique_ptr 错误使用已删除函数 'std::unique-ptr'