排序在 C 中因地址边界错误而崩溃

sorting crashes with address boundary error in C

这是我的问题的最小可重现示例。我有一些数据结构,我需要按字典顺序排序。但是当我 运行 sort() 函数崩溃时。我认为问题可能是我allocate/reallocatememory的方式,但没有弄清楚它到底是什么。

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

int num_id = 5;
typedef struct data_id
{
    char *id;
    int marker;
} data_id;
data_id *buffer_sort, *nodeList;

void sort()
{
    buffer_sort = malloc(sizeof(nodeList)*100);
    for (int i = 0; i < num_id; ++i)
    {
        for (int j = i + 1; j < num_id; ++j)
        {
            // swapping strings if they are not in the lexicographical order
            if (strcmp(nodeList[i].id, nodeList[j].id) > 0)
            {
                strcpy(buffer_sort[i].id, nodeList[i].id);
                buffer_sort[i].marker = nodeList[i].marker;

                strcpy(nodeList[i].id, nodeList[j].id);
                nodeList[i].marker = nodeList[j].marker;

                strcpy(nodeList[j].id, buffer_sort[i].id);
                nodeList[j].marker = buffer_sort[i].marker;
            }
        }
    }
    free(buffer_sort);
}

void fill(){
    nodeList = malloc(sizeof *nodeList*5);

    nodeList[0].id = "a";
    nodeList[1].id = "e";
    nodeList[2].id = "c";
    nodeList[3].id = "b33";
    nodeList[4].id = "cc";
    nodeList[0].marker = 0;
    nodeList[1].marker = 255;
    nodeList[2].marker = 0;
    nodeList[3].marker = 2;
    nodeList[4].marker = 0;
}

int main(){
    fill();
    sort();
    
    for (int i = 0; i<num_id; ++i){
        printf("Marker:%d\n", nodeList[i].marker);
        printf("ID:%s\n\n", nodeList[i].id);
    }
}

交换字符串看起来很可疑。 strcpy(buffer_sort[i].id, nodeList[i].id) 尝试复制到未初始化的 .id,这是 未定义的行为

使用简单的 struct 交换。

// strcpy(buffer_sort[i].id, nodeList[i].id);
// buffer_sort[i].marker = nodeList[i].marker;
// strcpy(nodeList[i].id, nodeList[j].id);
// nodeList[i].marker = nodeList[j].marker;
// strcpy(nodeList[j].id, buffer_sort[i].id);
// nodeList[j].marker = buffer_sort[i].marker;

// Swap the struct
data_id tmp = nodeList[i];
nodeList[i] = nodeList[j];
nodeList[j] = tmp;

使用 buffer_sort = malloc(sizeof(nodeList)*100); --> buffer_sort = malloc(sizeof *buffer_sort * 100); 以避免尺寸错误。

sizeof(nodeList)是一个指针的大小。 sizeof *buffer_sortbuffer_sort 指向的一个对象的大小。

IAC,buffer_sort不需要。


可能存在其他问题。