Я новичок здесь, и у меня есть к вам вопрос.У меня проблема с памятью из-за задания в универе.Я программирую систему Евровидения и использую метод структур.Я скопировал здесь проблемные функции, включая вывод valgrind.Я хотел бы за некоторую помощь, спасибо.
eurovisionRunGetFriendlyStates function:
}
if(eurovision == NULL){
return NULL;
}
int *stateScoresId = malloc(eurovision->stateSize*sizeof(int));
if(stateScoresId == NULL){
return NULL;
}
int *stateScores = malloc(eurovision->stateSize*sizeof(int));
if(stateScores == NULL){
free(stateScoresId);
return NULL;
}
int *statesCompareId = malloc(eurovision->stateSize*sizeof(int));
if(statesCompareId == NULL){
free(stateScores);
free(stateScoresId);
return NULL;
}
getSameStates(eurovision, stateScoresId, stateScores, statesCompareId);
char** stateNames = malloc(sizeof(char*)*eurovision->stateSize);
if(stateNames == NULL){
free(statesCompareId);
free(stateScores);
free(stateScoresId);
return NULL;
}
if(fillNames(eurovision, stateNames) == -1){
free(stateNames);
free(statesCompareId);
free(stateScores);
free(stateScoresId);
return NULL;
}
sortByName(eurovision, statesCompareId, stateScoresId,
eurovision->stateSize, stateNames);
return makeFriendlyList(eurovision, statesCompareId, stateScoresId);
}sortByName function:
if (n == 1) {
return;
}
int i_max = indexOfMaxChar(names, n);
int j_max = findState(eurovision, statesId, names, i_max);
swap(&statesCompareId[n-1], &statesCompareId[j_max]);
swap(&statesId[n-1], &statesId[j_max]);
swapString(&names[n-1], &names[i_max]);
sortByName(eurovision, statesCompareId, statesId, n-1, names);
}swap function:
int tmp = *p;
*p = *q;
*q = tmp;
}
the valgrind output:
{
==28086== Invalid read of size 4
==28086== at 0x401C94: swap (eurovision.c:599)
==28086== by 0x402023: sortByName (eurovision.c:688)
==28086== by 0x402077: sortByName (eurovision.c:690)
==28086== by 0x402077: sortByName (eurovision.c:690)
==28086== by 0x4016C0: eurovisionRunGetFriendlyStates (eurovision.c:476)
==28086== by 0x4048AB: testRunGetFriendlyStates (eurovisionTests.c:341)
==28086== by 0x404C73: main (eurovisionTestsMain.c:23)
==28086== Address 0x5203cc4 is 12 bytes before a block of size 0 alloc'd
==28086== at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==28086== by 0x401560: eurovisionRunGetFriendlyStates (eurovision.c:441)
==28086== by 0x4048AB: testRunGetFriendlyStates (eurovisionTests.c:341)
==28086== by 0x404C73: main (eurovisionTestsMain.c:23)
}