Hello!
I have searched through the forum for help on my problem but I haven't seen one that applies to me. If there exists one, please forgive me for this post. I know for sure that I have have done something wrong but I can't understand what:
Code:
...
move(&spock.ship);
SDL_BlitSurface(spock.ship.graph, NULL, screen, &spock.ship.pos);
for (i = 0; i < SPOCK_LASERS; i++) {
if ((p = spock.lasers[i]) == NULL) continue;
move(p);
SDL_BlitSurface(p->graph, NULL, screen, &p->pos);
// Beam reached top of screen
if (spock.lasers[i]->pos.y == 0) {
free(spock.lasers[i]);
spock.lasers[i] == NULL;
}
}
if (SDL_GetTicks()-last_flip > TBF) {
last_flip = SDL_GetTicks();
SDL_Flip(screen);
}
// Controls
while (SDL_PollEvent(&event)) {
...
When I run the program (and reaching the free-statement, nothing works as expected. What I want to is to free the area (which was allocated by malloc()) and set the pointer to NULL. But that is not going to happen.
What the computer really does is something strange (stepped one line at a time in kdevelop and gdb, I am using Debian Linux):
1. When spock.lasers[i]->pos.y == 0 evaluates true it seems to run the free() statement.
2. It jumps directly up to for() statement, not running "spock.lasers[i] == NULL;"?!
3. The program continues.
4. When it does the check again (which it does because it is in the "giant" game loop), the pointer still isn't null and therefor assumed to be valid.
5. The free() statement is reached again and same thing happens (not running "spock.lasers[i] == NULL;", but instead run the for() loop). This is odd since it deallocated same memory twice without complains.
6. The third time the free() statement is called, libc send me SIGABRT.
When I compile the program I do get a warning: statement with no effect (pointing to "spock.lasers[i] == NULL;"). So obviously there is something I do wrong, and I hope someone kind enough to help me.
My theory is that free() works like some kind of continue (and return, I have tried to put the code in a separate function with same results). If so it does not say so in the manual, I will have no clue how to NULL that pointer and free() is just another function so it should be imposible that it works like this, right?!
Thanks for taking time with this post.
PS: If you want a little sense what I am doing is that the player (called Spock in the code) fires a laser beam (stored in spock.lasers[] using malloc). When it reaches the top of the screen, it should disappear from the program completely. DS