我想在C中寫入數據結構堆棧。我的堆棧的每個元素都是一個字符串。以下是我使用的三個文件。第一個是主要的,其他的是頭文件stack.h和文件stack.c。我將stackElement聲明爲指向元素的指針。 stackT是一個定義堆棧的結構。我試圖釋放分配內存時出現問題,因爲當我運行valgrind時,我得到Valgrind塊丟失
==31235== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
==31235==
==31235== 1 errors in context 1 of 2:
==31235== Invalid free()/delete/delete[]/realloc()
==31235== at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31235== by 0x400893: StackDestroy (in /test)
==31235== by 0x400B61: main (in /test)
==31235== Address 0x51fc150 is 0 bytes inside a block of size 4 free'd
==31235== at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31235== by 0x400B55: main (in /test)
24 bytes in 1 blocks are definitely lost in loss record 1 of 1
請問您能幫我嗎?
int main(){
stackT S;
int r = 3, i;
StackInit(&S, 2, r);
printf("test\n");
stackElementT s0;
s0 = malloc((r + 1) * sizeof(unsigned char));
memset(s0, 1, r + 1);
s0[r] = 0;
for (i = 0; i < r; i++) {
s0[i] = random() & 0xff;
}
StackPush(&S, s0);
free(s0);
StackDestroy(&S);
return 0;
}
stack.h
typedef unsigned char * stackElementT;
typedef struct {
stackElementT *contents;
int maxSize;
int top;
} stackT;
stack.c
void StackInit(stackT *stackP, int maxSize, int r) {
stackElementT *newContents;
int i;
r = 3;
newContents = malloc(sizeof(stackElementT) * maxSize);
if (newContents == NULL) {
fprintf(stderr, "Insufficient memory to initialize stack.\n");
exit(1);
}
for (i = 0; i < maxSize; i++) {
if ((newContents[i] = malloc(r * sizeof(stackElementT))) == NULL) {
fprintf(stderr, "Insufficient memory to initialize stack.\n");
exit(1);
}
}
stackP->contents = newContents;
stackP->maxSize = maxSize;
stackP->top = -1; /* I.e., empty */
}
void StackDestroy(stackT *stackP) {
int i;
for (i = 0; i < stackP->maxSize; i++)
free(stackP->contents[i]);
free(stackP->contents);
stackP->contents = NULL;
stackP->maxSize = 0;
stackP->top = -1;
}
void StackPush(stackT *stackP, stackElementT element) {
if (StackIsFull(stackP)) {
fprintf(stderr, "Can't push element on stack: stack is full.\n");
exit(1);
}
stackP->contents[++stackP->top] = element;
}
編輯:
使用下面的答案我評論免費線(S0),但我得到的下一個錯誤:
==31855== 24 bytes in 1 blocks are definitely lost in loss record 1 of 1
==31855== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31855== by 0x4007F9: StackInit (in /test)
==31855== by 0x400AA9: main (in /test)
'for(i = 0; i < stackP-> maxSize; i ++)free(stackP-> contents [i]);'這會嘗試釋放空的堆棧槽。 –
@ColonelThirtyTwo爲什麼他試圖釋放空棧空位? – Juan
嘗試將'--track-origins = yes'標誌添加到valgrind中,如果我正確記得,它應該顯示內存分配的位置。 –