我试图在CS107 - 编程范例(斯坦福大学的在线课程)中实现讲座5和6中所示的通用堆栈。 下面的代码,代表了讲座中提供的一个例子,编译,但似乎没有表现一致,因为我经常得到一个断言失败。
我注意到了Geany和gcc($ gcc --version
gcc (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.
答案 0 :(得分:8)
您在设置之前检查s->elemSize
。你正在使用一个未初始化的变量。
修复:assert(elemSize > 0)
(检查函数参数,而不是s
的成员),或assert
转让后执行s->elemSize = elemSize
。