我是新来的,有一个问题要问你。由于uni中的分配,我遇到了内存问题。 我对eurovision系统进行编程,并使用structs方法。 我在这里复制了有问题的函数,包括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)
}