c - 使用 malloc、C 在终端中打印奇怪的内容

标签 c malloc

我尝试使用malloc 首先为数组分配一些空间,然后使用realloc 来扩展数组。该程序可以编译,但当我运行该程序时,我在终端中得到一些奇怪的内存打印。终端会显示如下内容:========内存映射=========,然后是一堆数字和其他内容。

在我的程序中,我使用 malloc 如下:

struct station *addStation(struct station *graph, struct station newStation){
    graph = realloc(graph, sizeof(graph)+sizeof(struct station));
// Count the rows of graph[] here and add newStation to the end.
}

int main(){
    struct station *graph;
    graph = malloc(145*sizeof(struct station));
    graph = loadStations();
    newStation = graph[27];

    graph = addStation(graph, newStation);
}

我用错了吗?

最佳答案

您正在覆盖内存所在的指针:

graph = malloc(145*sizeof(struct station));
graph = loadStations(); // malloc'd memory is lost here

如果您想向内存添加一些数据,则需要将其作为指针传递:

loadStations(graph);

此外,您的 sizeof(graph)+sizeof(struct station) 仅将数据保留到 1 个指针和 1 个站,这不是您想要的。您需要传递现有的尺寸信息:

struct station * addStation(struct station * graph, size_t * count, struct station newStation){
    size_t newCount = *count + 1;
    graph = realloc(graph, newCount * sizeof(struct station));
    if(!graph)
        return 0;
    *count = newCount;
    // Copy new station here
    return graph;
}

并在main中调用:

    temp = addStation(graph, &graphCount, newStation);
    if(temp)
        graph = temp;

关于c - 使用 malloc、C 在终端中打印奇怪的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19022515/

相关文章:

c - 使用 static 而不是 malloc - C 语言

c - 函数内部使用malloc形成字符串时的段错误(11)

c - 程序在重新分配内存时导致内存损坏

在C中递归创建并遍历二叉树

c - 打破平局以四舍五入到 c 中最接近的可表示 float ?

c - 用户输入文件

c - 为什么我们不能动态分配一个指向函数的指针?

c - for 循环接受比循环条件多一个值

c - 在c中使用sin函数得到错误的值

c++ - 使用动态对象分配标准 vector 内容