0

Accessing elements of a pointer pointer WITHIN a function after passing it as an argument causes my program to crash.

For example

INITIALIZATION:

edge **graph;
graph = malloc(e*sizeof(edge));
for(int i = 0; i< e;i++){
    graph[i] = malloc(sizeof(edge));
}

After initialization, this works:

printf("%d\n", graph[i]->cost);

But after passing it on to a function it crashes:

Function(edge **graph){
    //stuff
    printf("%d\n", graph[i]->cost); //this causes a crash
}

What's causing this? Thanks in advance! :D

5
  • 6
    graph = malloc(e*sizeof(edge)); should be graph = malloc(e*sizeof(*graph)); or malloc(e*sizeof(edge*)) Commented Nov 19, 2015 at 10:07
  • 6
    You should post minimal and complete program that demonstrates the behaviour. You may be calling the function incorrectly. Commented Nov 19, 2015 at 10:09
  • Pointer Pointer? I think u meant "Dual pointer"./ Pointer to pointer. Commented Nov 19, 2015 at 10:10
  • 4
    Or you may be corrupting the memory somewhere after intialisation and before the function call. So yes, agree with @user694733, please post a Minimal Complete and Verifiable Example. Commented Nov 19, 2015 at 10:11
  • 1
    @milevyo What do you mean? I simply asked OP to provide more details, as question in it's current form doesn't necessarily reveal the real problem. Others seem to agree, question is not clear enough yet. Commented Nov 19, 2015 at 10:43

1 Answer 1

1

graph[i] will be of type edge * (i.e. pointer to edge).

Generally speaking, malloc() should be used to allocate a multiple of the size being pointed to. graph is of type edge **. Which means the size supplied to malloc() should be a multiple of the size of an edge *. Your code is allocating a multiple of sizeof(edge) which (unless you get lucky) is not equal to sizeof(edge *).

Hence your malloc() call should look something like graph = malloc(e * sizeof(edge *)) or (better, since it works out what graph points at without you having to scratch your head) graph = malloc(e * sizeof(*graph)).

If you don't do that, the result of using dereferencing graph (e.g. graph[i]->cost gives undefined behaviour. Avoiding undefined behaviour is the reason you need to ensure (among other things) that the sizes allocated using malloc() are valid. One symptom of undefined behaviour is a crash in some circumstances but not in others - such as you're seeing the same code doing different things in different contexts.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.