Reputation: 429
So I am working on an implementation of stack in C by using structs, and the following thing is bothering me
typedef struct {
int vrh, polje[MAXSTOG];
} Stog;
void init_stog(Stog *stog) {
stog->vrh = -1;
}
int dodaj(int element, Stog *stog) {
if(stog->vrh == MAXSTOG-1) {
return 0;
}
stog->vrh++;
stog->polje[stog->vrh] = element;
return 1;
}
int skini(int *element, Stog * stog) {
if(stog->vrh < 0)
return 0;
*element = stog->polje[stog->vrh];
stog->vrh--;
return 1;
}
int main(){
Stog *stog;
init_stog(stog);
dodaj(5, stog);
dodaj(3, stog);
dodaj(2, stog);
int a;
skini(&a, stog);
printf("%d ", a);
skini(&a, stog);
printf("%d ", a);
return 0;
}
Why does Stog *stog; works, even though the pointer doesn't point to anything. I understand that Stog is object_name, and it is already instantiated, so that would only be that pointer points to instantiated struct, but I don't understand the syntax when pointer is added, and I couldn't find an explanation for that anywhere.
Could you explain me is that just a c syntax thing, or I misunderstood something?
Upvotes: 2
Views: 170
Reputation: 727077
It "works" by mistake (which is another way of saying "it does not work").
When you start your program, variable stog
has some random combination of bits. Your program interprets that combination as an address, and starts writing data into it. When you get lucky, your program crashes on you, so you know that something needs to be fixed.
When you get unlucky, the program runs to completion, and even produces the expected output. The program is not correct, though, and needs to be fixed. In particular, it may not run on a different hardware, or may produce different result or crash the next time you run it. You can use memory profiling tools, such as valgrind, to find hidden errors like that.
One way of fixing the program is to declare stog
as a variable, not as a pointer, and pass &stog
whenever a pointer is needed.
Upvotes: 4
Reputation: 983
What you're currently doing is undefined behavior. You're using an uninitialized pointer and using it like it points at an actual struct. As the name says, the behavior is undefined, anything could happen. It might work for you now, but on some computer, somewhere, the exact same code might make the thing crash, blow up, or worse. So you could call yourself lucky in this case, but I would update your code so your pointer actually points somewhere valid.
Upvotes: 4