tags:

views:

154

answers:

5
typedef struct pilha Pilha;

struct pilha
{
    char metodo[31];
    Pilha *next;
};

void create_empty_stack(Pilha *Stack)
{
    Stack->next = NULL;
}

int main()
{
    Pilha *Stack;

    create_empty_stack(Stack);
}

Gives me an execution error.

What's the problem with this function?

+1  A: 

Consider what Stack points to at the line in *Criar_Pilha_vazia()*. The dereference for assignment points to a random place. In a virtual memory environment, it will segfault.

wallyk
+2  A: 

You are passing an uninitialized variable Stack into the function Criar_Pilha_vazia. It will crash as soon as you do the first dereference on Stack in your function.

Starkey
to be fair, the behavior is undefined. local variables are uninitialized or zeroed so theoretically you could get a valid pointer.
luke
@luke first time i heard of anti-Murphy .. is something even has an remote chance of going correct .. it just may !!!
Vardhan Varma
When in doubt, assume it formats your hard drive.
Nathan Ernst
Oh yeah. The worst thing it can do is *appear* to work. Then you go on and depend on it, and when other things don't work due to the dangling pointers you have a real mystery that can take a lot of effort to identify.
RBerteig
+5  A: 

If you are gonna point, you should point at something.....

James Curran
aww, but pointing is impolite! :)
Timothy
+7  A: 

This is a classic mistake that beginners do.

Let's take a look at your main function:

int main()
{
    Pilha* Stack; // This line is your problem!

    create_empty_stack(Stack);
}

If you remember pointers, the declaration Pilha* Stack; makes Stack be a memory pointer. But right now it doesn't point to anything, because you did not reserve memory for an object of type Pilha!

Your program crashes because create_empty_stack() tries to access next, a member of this object (remember that this object still doesn't exist).

So, what you should be doing instead is:

int main()
{
   // Reserve space in memory for one Pilha object and 
   // make Stack point to this memory address.
    Pilha* Stack = (Pilha*) malloc(sizeof(Pilha)); 

    create_empty_stack(Stack);
}

Or a much simpler approach:

int main()
{
    Pilha Stack; // Declare a new Pilha object

    // and pass the memory address of this new object to create_empty_stack()
    create_empty_stack(&Stack); 
}
karlphillip
+3  A: 

you'd better create your function like this:

Pilha* create_empty_stack()
{

    Pilha *Stack = malloc(sizeof(Pilha))
    Stack->next = NULL;
    return Stack;
}
maroxe