Stephane-D / SGDK

SGDK - A free and open development kit for the Sega Mega Drive
https://www.patreon.com/SGDK
MIT License
1.75k stars 187 forks source link

Error in when using -03 optimization #126

Closed moon-watcher closed 6 years ago

moon-watcher commented 6 years ago

I've been using this linked list code https://github.com/moon-watcher/GrielsQuest/blob/master/game/libs/vram.c in my previous projects.

Due to a -03 optimization, current SGDK throws an error error in line 87 https://github.com/moon-watcher/GrielsQuest/blob/d7da36ac310aa2f6654588bf4ea891b86ceaebc7/game/libs/vram.c#L87

node->next = new;

I changed to -01 and the rom worked again

Stephane-D commented 6 years ago

To be honest i don't see immediately what is wrong and i'm almost certain this is not a "compiler bug". Still be careful if you use the memory manager (MEM_xxx calls), be sure that you don't mix calls from VInt callback and "main loop" in which case you can corrupt its state. Also maybe you don't know but there is a VRAM memory manager in SGDK ;) https://github.com/Stephane-D/SGDK/blob/master/inc/vram.h You create a VRAM region (with a specified size) then you just allocate out of it :)

moon-watcher commented 6 years ago

Found it! -03 optimization NEEDS this:

if (node)
    node->next = new;
Stephane-D commented 6 years ago

Oh indeed, i would even say you need it in all case and not only in -O3 as node can be null at this point. You are even doing that at the beginning :

if ( !node )
{
        _list = new;
}

And you don't update node so it remains null here.. not sure that is what you want. Also you should check for null for the whole piece of code (ans not only for node->next affectation) as it doesn't make sense to execute it if you don't use the 'new' block.