我正试图根据以下标头(stack.h)在C中实现堆栈:
#ifndef STACK_H
#define STACK_H
/* An element from which stack is consisting */
typedef struct stack_node_ss {
struct stack_node_ss *next; /* pointer to next element in stack */
void *value; /* value of this element */
} stack_node_s;
/* typedef so that stack user doesn't have to worry about the actual type of
* parameter stack when using this stack implementation.
*/
typedef stack_node_s* stack_s;
/* Initializes a stack pointed by parameter stack. User calls this after he
* has created a stack_t variable but before he uses the stack.
*/
void stack_init(stack_s *stack);
/* Pushes item to a stack pointed by parameter stack. Returns 0 if succesful,
* -1 otherwise.
*/
int stack_push(void *p, stack_s *stack);
/* Pops item from a stack pointed by parameter stack. Returns pointer to
* element removed from stack if succesful, null if there is an error or
* the stack is empty.
*/
void *stack_pop(stack_s *stack);
#endif
然而,作为C的新手,我一直停留在stack_init函数上,我已经在stack.C中编写了
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
void stack_init(stack_s *stack) {
(*stack)->value = NULL;
(*stack)->next = NULL;
}
主程序开始于:
int *tmp;
stack_s stack;
stack_init(&stack);
这使我的程序崩溃:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000008
0x0000000100000abf in stack_init (stack=0x7fff5fbffb30) at stack.c:6
6 (*stack)->value = NULL;
你能告诉我正确的路线吗?非常感谢。
您必须为**stack
本身分配内存:
*stack = malloc(sizeof(**stack));
但请不要键入def指针类型。这真的很令人困惑,很难阅读。最好按值传递指针,并将其留给调用者来存储指针,如下所示:
typedef struct stack_node_t
{
struct stack_node_t * next;
/* ... */
} stack_node;
stack_node * create_stack()
{
stack_node * res = calloc(1, sizeof(stack_node));
return res;
}
void destroy_stack(stack_node * s)
{
if (!next) return;
stack_node * next = s->next;
free(s);
destroy_stack(next);
}
// etc.
然后你可以说:
stack_node * s = create_stack();
// use s
destroy_stack(s);
s = NULL; // some people like this
您正在取消引用未初始化的指针,从而导致未定义的行为。
因为这个函数正在创建一个新的堆栈,所以您需要为堆栈分配一些动态内存,然后将指针设置为指向新分配的内存:
void stack_init(stack_s *stack) {
*stack = malloc(sizeof(**stack)); // create memory for the stack
(*stack)->value = NULL;
(*stack)->next = NULL;
}
stack_s stack;
stack_init(&stack);
然后您应该有一个名为stack_destroy
的函数,它将free
动态内存并将指针设置为NULL
:
void stack_destroy(stack_s *stack) {
free(*stack);
*stack = NULL;
}
您应该将堆栈初始化为NULL,而不是向其推送NULL值:
void stack_init(stack_s *stack) {
*stack=NULL;
}