I would like to know why valgrind
says:
==9952== 30 bytes in 6 blocks are definitely lost in loss record 1 of 1
==9952== at 0x4C2BF0E: realloc (vg_replace_malloc.c:662)
==9952== by 0x40131F: setCharsPositions (paramsExec.c:99)
==9952== by 0x400CF3: main (main.c:87)
I can't figure out what's the problem with my realloc()
(you don't have to say that reallocating memory by one every time is inefficient...); the variable char **passwordSet2
is global — maybe that is the problem... If I'm doing something wrong, please let me know! I'm going crazy!
void setCharsPositions(char *charsPos){
int i, k;
char *posStr = NULL;
for(i = 0; i < strlen(charsPos); i++){
posStr = malloc(sizeof(char));
if(charsPos[i] == '['){
for(k = 0, i++; charsPos[i] != ','; i++, k++){
posStr[k] = charsPos[i];
posStr = realloc(posStr, (k+2)*sizeof(char));
}
posStr[k] = '\0';
passwordSet2[atoi(posStr)-1] = malloc(sizeof(char));
for(k = 0, i++; charsPos[i] != ']'; i++, k++){
passwordSet2[atoi(posStr)-1][k] = charsPos[i];
passwordSet2[atoi(posStr)-1] = realloc(passwordSet2[atoi(posStr)-1], (k+2)*sizeof(char));
}
passwordSet2[atoi(posStr)-1][k] = '\0';
}
free(posStr);
}
}
passwordSet2[atoi(posStr)-1] = malloc(sizeof(char));
If passwordSet2[atoi(posStr)-1]
was previously assigned, this leaks memory. That is, you have a leak if the same value of posStr occurs more than once. The lost memory would be from a previous realloc, so that's what valgrind will report. (It would help if you would point out which is line 662.) If the same value of posStr is occurring more than once but isn't supposed to, then you need to check for that. If it's allowed to occur more than once, then you should add a call to free
:
free(passwordSet2[atoi(posStr)-1]);
passwordSet2[atoi(posStr)-1] = malloc(sizeof(char));
The first occurrence of free
, when passwordSet2[atoi(posStr)-1]
is NULL, is a no-op.
Also, you're not checking for NULL returns from malloc and realloc, though those would cause your program to crash, not just leak.
Finally, for clarity and possibly efficiency, I would urge you to put atoi(posStr)-1 into a variable instead of repeating it.