其他分享
首页 > 其他分享> > 索引“已分配”数组时出现分段错误

索引“已分配”数组时出现分段错误

作者:互联网

我已经为这个问题苦苦挣扎了几个小时,而我对所发生的事情一无所知.这是program.c的代码:

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

#define SPACE 32
#define INITIAL 4

typedef struct {
    char *town;
    char *country;
} town_t; 

typedef struct {
    int num_towns, current_size;
    town_t **towns_list;
} index_t;

int main(int argc, char *argv[]) {

    index_t town_index;
    town_index.current_size = INITIAL;
    town_index.towns_list = malloc(town_index.current_size * sizeof(*(town_index.towns_list)));
    assert(town_index.towns_list != NULL);

    printf("Step: %d\n", 1);
    town_index.towns_list[0]->town = malloc(4 * sizeof(*(town_index.towns_list[0]->town)));
    printf("Step: %d\n", 2);
    assert(town_index.towns_list[0]->town != NULL);

    return 0;
}

在Linux上,运行方式如下:

./program
Step: 1
Segmentation fault

但在Windows上它会打印出来

program.exe
Step: 1
Step: 2

如我所料,这确实无济于事.但是,对于Linux输出,显然第一个print语句正在执行,而不是第二个,这使我认为两者之间的界线是错误的.特别是,我认为执行town_index.towns_list [0]会引起我一些问题,但我不能说为什么.

这是一个相对复杂的数据结构,所以也许在某个时候我迷路了.基本上,town_index是一个索引结构,其中包含towns_list中的当前城镇数和current_size,这反映了当前可用于保存城镇的空间.它还包含一个指向town_ts的指针数组,该数组包含名称和国家/地区作为字符串.

我尝试使用Valgrind,但实际上并没有太大帮助.这是给想要看的人的Pastebin.

这是我在另一个程序中遇到的情况的简化场景,因此不要介意魔术数字和其他什么.

这是在VirtualBox Linux Mint 64位上.

无关的问题,如果有人可以:我如何让Valgrind显示精确的线条?我在网上其他任何地方都能看到它,但是我的输出只是告诉我程序和函数所在的文件夹,并没有太大帮助.

解决方法:

您初始化了town_index.towns_list,但未初始化town_index.towns_list [0],因此Town_index.towns_list [0]-> town是未定义的行为.

你错过了类似的东西

for (int i = 0; i < town_index.current_size; ++i)
    town_index.towns_list[i] = malloc(sizeof **town_index.towns_list);

对于第二维.

标签:malloc,indexing,c-3,linux,segmentation-fault
来源: https://codeday.me/bug/20191026/1937870.html