for(k=i; k<MAXRECORDS; k++) {
if(slist->servers_ptr[k+1] != NULL) {
slist->servers_ptr[k] = slist->servers_ptr[k+1];
} else slist->servers_ptr[k] = NULL;
}
When I run valgrind, I get an error of invalid size 8.
I assume this has something to do with a border case in my for loop, but I don’t understand logically how it’s happening.
EDIT: It was pointed out that on the last round of the for loop, accessing servers_ptr[k+1] is outside of the array, causing valgrind errors. I have since updated my code to:
for(k=i; k<MAXRECORDS-1; k++) {
if(slist->servers_ptr[k+1] != NULL) {
slist->servers_ptr[k] = slist->servers_ptr[k+1];
if(k==MAXRECORDS-2)slist->servers_ptr[k+1] = NULL;
} else slist->servers_ptr[k] = NULL;
}
I still get the errors in valgrind. Did I update it incorrectly?
It’s almost certainly because you’re going beyond the end of the array. The maximum value of
kisMAXRECORDS-1and you’re usingk+1in your expressions.That means you’ll be accessing
array[MAXRECORDS]where the index should be limited to between0andMAXRECORDS - 1inclusive.It’s difficult to see what you’re trying to do without more context but the fix may be as simple as using
k < MAXRECORDS - 1as theforloop continuing condition (the bit in the middle):The other possibility is an invalid value of
i, like-1for example, which would cause the problem at the other end of the array. This is probably less likely since I’m assuming you’re deleting elementiby shifting all the other elements down (as in:iwill be set to a valid index).That’s not a memory leak by the way, simply a memory corruption. Memory leaks are when you allocate memory and then lose the pointers to them so that they can never be freed, something like:
where only the last allocation is accessible.
By the way, if a shuffling deletion is what you’re after, it would be better done (in my opinion) as:
The extra condition stops where the next element is NULL and places NULL into that position. That should work fine and has the advantage of being less complex.