我正在尝试实现CS107-编程范例(斯坦福大学在线 class )的第5和第6讲解中说明的通用堆栈。
以下代码(代表演讲中的示例)可以编译,但由于我经常会断言失败,因此似乎无法保持一致。
我已经注意到Geany和gcc($ gcc --versiongcc (Debian 6.3.0-18) 6.3.0 20170516
)中的行为,但是没有注意到'https://www.tutorialspoint.com/compile_c_online.php'上的行为,所以我想知道这是由gcc中的某种原因还是我现在似乎看不到的错误引起的。
码:
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include <assert.h>
typedef struct {
void *elems;
int elemSize;
int logLen;
int allocLen;
} stack;
void StackNew(stack *s, int elemSize);
void StackDispose(stack *s);
void StackPush(stack *s, void *elemAddr);
void StackPop(stack *s, void * elemAddr);
void StackNew(stack *s, int elemSize)
{
assert(s->elemSize > 0);
s->elemSize = elemSize;
s->logLen = 0;
s->allocLen = 4;
s->elems = malloc(4 * elemSize);
assert(s->elems != NULL);
}
void StackDispose(stack *s)
{
free(s->elems);
}
static void StackGrow(stack *s)
{
s->allocLen *= 2;
s->elems = realloc(s->elems, s->allocLen * s->elemSize);
}
void StackPush(stack *s, void *elemAddr)
{
if(s->logLen == s->allocLen)
StackGrow(s);
void *target = (char *) s->elems + s->logLen * s->elemSize;
memcpy(target, elemAddr, s->elemSize);
s->logLen++;
}
void StackPop(stack *s, void *elemAddr)
{
void *source = (char *) s->elems +
(s->logLen - 1) * s->elemSize;
memcpy(elemAddr, source, s->elemSize);
s->logLen--;
}
int main(void)
{
const char *friends[] = {"Al", "Bob", "Carl"};
stack stringStack;
StackNew(&stringStack, sizeof(char *));
int i;
for (i = 0; i < 3; i++){
char *copy = strdup(friends[i]);
StackPush(&stringStack, ©);
}
char *name;
for (i = 0; i < 3; i++) {
StackPop(&stringStack, &name);
printf("%s\n", name);
free(name);
}
StackDispose(&stringStack);
return 0;
}
几个连续执行的示例输出,没有任何源代码修改:
$ ./stack4
stack4: stack4.c:21: StackNew: Assertion 's->elemSize' > 0 failed.
Aborted
$ ./stack4
stack4: stack4.c:21: StackNew: Assertion 's->elemSize' > 0' failed.
Aborted
$ ./stack4
Carl
Bob
Al
$ ./stack4
Carl
Bob
Al
$ ./stack4
Carl
Bob
Al
$ ./stack4
stack4: stack4.c:21: StackNew: Assertion 's->elemSize' > 0' failed.
Aborted
$ ./stack4
stack4: stack4.c:21: StackNew: Assertion 's->elemSize' > 0 failed.
Aborted
$ ./stack4
Carl
Bob
Al
$ ./stack4
stack4: stack4.c:21: StackNew: Assertion 's->elemSize' > 0' failed.
最佳答案
您需要先检查s->elemSize
,然后再进行设置。您正在使用未初始化的变量。
修复:要么assert(elemSize > 0)
(检查功能参数,而不是s
的成员),或者在assert
分配后执行s->elemSize = elemSize
。