Arkantos Arkantos - 11 days ago 5x
Linux Question

Getting segmentation fault when indexing a 'mallocced' array

I've been struggling with this one for a few hours now and I'm at a loss as to what's happening. This is the code for 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;

On Linux this is how it runs:

Step: 1
Segmentation fault

but on Windows it prints out

Step: 1
Step: 2

as I'd expect, which really isn't helping. For the Linux output, however, clearly the first print statement is being executed but not the second, which would lead me to think that the line between is that one at fault. Particularly, I think doing
is causing me issues, but I cannot say why.

This is a relatively complex data structure, so maybe I'm getting lost at some point. Basically
is meant to be a index struct that contains the current number of towns in
which reflects the space currently available to save towns. It also contains an array of pointers to
s which contain the name and country as strings.

I've tried to use Valgrind, but it's really not helping out much. Here's a Pastebin for those who want to see.

This is a simplified scenario of what I was experiencing in another program, so don't any mind magic numbers and whatnot.

This is on VirtualBox Linux Mint 64-bit.

Unrelated question, if anyone can: How do I get Valgrind to display the precise lines? I see that everywhere else online, but my output just tells me the folder in which the program and function is, which isn't much help.

mch mch

You initialized town_index.towns_list, but not town_index.towns_list[0], so town_index.towns_list[0]->town is undefined behaviour.

You missed something like

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

for the second dimension.