Since the type of cache->sets
is LRU **
, the type of cache->sets + i
is also LRU **
. When you assign the result to LRU *cur_lru
, I'd have expected you to get a compiler warning. (Are you building without warnings enabled?)
This assignment from incompatible pointer types means that you're writing into pointers in the sets
array as if they were fields of the LRU
structure.
edit: On more careful reading, I see you understand that subscripting should be right, and you're reporting that the code only works if you introduce this type error. I stand by the above, and in fact GCC reports "warning: assignment from incompatible pointer type", even without -Wall
.
The only other issue I can find in this code is that when you malloc
the sets
array, you size each element as sizeof(LRU)
, not sizeof(LRU *)
. However, whatever platform you're on almost certainly makes the LRU
struct bigger than a pointer to LRU
, so that shouldn't explain the symptom you're seeing.
Note that if you compile with optimization (gcc -O2
or similar), then the information that gdb
reports may be misleading. It's possible that when you introduce the type error, you're preventing gcc
from optimizing the initializations, and might be the only reason gdb
reports what you expect then.
I strongly encourage you to compile with gcc -Wall
and fix all the warnings. Then, if that hasn't fixed the problem, run your program under Valgrind to catch a variety of memory errors.