I have this function that always returns a valgrind read 2 error:
#define ForEachEst(r,s,i) for((i) = 0, (s) = group[r]->est[i]; (i) < grp[r]->est_count; (s) = group[r]->est[++i])
I’ve tried rewriting it with a conditional operator:
ForEachEst(r,s,i) for((i) = 0, (s) = group[r]->est[i]; (i) < grp[r]->est_count; ++i, (s) = group[r]->est[i >= grp[r]->est_count ? 0 : i])
And Valgrind is still throwing a read 2 error. This code in the program I’m working on already has existing code throughout it, so I cannot take out this function entirely. Any thoughts?
Example:
#define ForEachEst(r,s,i) for((i) = 0, (s) = group[r]->est[i]; (i) < grp[r]->est_count; (s) = group[r]->est[++i])
/* each grp[] has many sets[], and the indexes for the sets are grp->est[]. ex: grp[1] {sets[0], sets[5], sets[9]}, grp[1]->est[] {0, 5, 9}. group[r]->est_count is an int that says how many indexes there are in that group*/
int s;
int r;
int i;
ForEachEst(r, s, i) {
print("Grp: %d, Set: %d", r, s);
}
i + 1
is out of range on the last iteration. Why are you using 1-based indices anyway? If there’s a reason for it consider putting together a minimal reproducible example to demonstrates the issue and explain what you’re trying to accomplish.I’ve been putting just i there and it still didn’t work. I accidentally put the +1 as my example. I’ll edit it
Ok, so
group[++i]
is out of range on the last iteration. More context in the form of a minimal reproducible example would help.ok, I added an example, ty for your help! I tried to simplify the function earlier and I think it made it confusing, so I put the full thing.