通过将指针设置为NULL来初始化C中的堆栈

时间:2012-02-22 22:56:22

标签: c null initialization linked-list

我正在尝试根据以下标头(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;

你能暗示我走向正确的轨道吗?非常感谢。

3 个答案:

答案 0 :(得分:6)

您必须为**stack本身分配内存:

*stack = malloc(sizeof(**stack));

但请不要键入dede指针类型。这真令人困惑,难以阅读。最好按值传递指针并将其留给调用者来存储指针,如下所示:

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

答案 1 :(得分:2)

您正在取消引用未初始化的指针,导致未定义的行为。

因为此函数正在创建一个新堆栈,所以需要为堆栈分配一些动态内存,然后将指针设置为指向新分配的内存:

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;
}

答案 2 :(得分:-1)

您应该将堆栈初始化为NULL - 不要将NULL值推送到它:

void stack_init(stack_s *stack) {
    *stack=NULL;
}
相关问题