malloc():在一个奇怪的地方内存损坏

malloc(): memory corruption in a weird place

几个小时以来,我一直在处理一个恼人的内存损坏错误。我已经检查了这里的每个相关线程,但我无法修复它。

首先,我正在用 C 编写一个简单的终端。我正在解析管道 (|) 和重定向(>、< 等)符号之间的命令并将它们放入队列中。没什么复杂的!

这是队列的数据结构;

struct command_node {
    int index;
    char *next_symbol;
    struct command_node *nextCommand;
    int count;
    char **args;
};

当我在 **args 指针中存储小字符串时,一切正常。但是,当其中一个参数很长时,我会收到 malloc(): memory corruption 错误。例如,以下第一个命令工作正常,第二个命令导致错误

   1st:  ls -laF some_folder | wc -l

   2nd:  ls -laF /home/enesanbar/Application | wc -l

我 运行 调试器,它表明对队列中新节点的 malloc() 调用导致错误。

newPtr = malloc( sizeof(CommandNode) );

我正在仔细分配字符串数组并在完成后释放它们,如下所示:

    char **temp = NULL;
    temp = malloc(sizeof(char*) * number_of_args);

    /* loop through the argument array */
    for (i = 0; i < number_of_args; i++) {
        /* ignore the remaining commands after ampersand */
        if (strcmp(args[i], "&") == 0) return;

        /* split commands by the redirection or pipe symbol */
        if (!isSymbol(args[i])) {
            temp[count] = malloc(sizeof(strlen(args[i])) + 1);
            strcpy(temp[count], args[i]);
            count++;

            /* if it is the last argument, assign NULL to the symbol in the data structure */
            if (i + 1 == number_of_args) {
                insertIntoCommands(&headCommand, &tailCommand, temp, NULL, count);
                for (j = 0; j < count; j++) free(temp[j]);
                count = 0;  // reset the counter
            }

        }
        else {
            insertIntoCommands(&headCommand, &tailCommand, temp, args[i], count);
            for (j = 0; j < count; j++) free(temp[j]);
            count = 0;  // reset the counter
        }
    }

我一定是漏掉了什么,或者我不知道 **args 字段和新节点的分配,尽管我以前没有做过。

but how could wrapping a number around the sizeof cause an error in the allocation of a node? I'm just trying to understand out of curiosity.

就像我在评论中所说的那样,您尝试获取 strlen 函数内部指针的大小,而不是通过该函数提供的长度。

请看以下内容:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>


int main(void){
    char *name = "Michi";
    size_t length1, length2;

    length1 = strlen(name);
    length2 =  sizeof strlen(name);

    printf("Length1 = %zu\n",length1);
    printf("Length2 = %zu\n",length2);
    return 0;
}

输出:

Length1 = 5
Length2 = 8

还有一件事,在你free(temp[j])之后别忘了free(temp)

像这样:

#include <stdio.h>
#include <stdlib.h>


int main(void){
    long unsigned int size = 2,i;
    char **array;

    array = malloc(sizeof(char*) * size * size);

    if (array == NULL){
        printf("Error, Fix it!\n");
        exit(2);
    }

    for (i = 0; i < size; i++){
         array[i] = malloc(sizeof(char*) * 100);
    }

    /* do code here */

    for (i = 0; i < size; i++){
         free(array[i]);
    }
    free(array);

    return 0;
}