在C中动态增长堆栈

时间:2013-01-22 15:26:44

标签: c segmentation-fault stack

我在分配方面遇到了一些麻烦。我应该实现一个动态增长的堆栈,当它已满时将其大小加倍,当它为1/4满时将其减半。由于我是一名C初学者并且不熟悉指针,因此我查看了一些示例,这是我提出的代码。

它实际上在没有警告的情况下编译gcc,但在我尝试运行它时会产生“Segmentation fault”。我发现这可能与破碎的指针有关,但我没有看到任何错误,如果有人能为我指出它会很高兴。

干杯

# ifndef STACK_H
# define STACK_H
# include "stdlib.h"

typedef struct stack {
  int *stack;
  int used;
  int size;
} stack;

stack* stck_construct() {
    stack *stck;
    stck->stack = (int *)malloc(10 * sizeof(int));
    stck->used = 0;
    stck->size = 10;
    return stck;
}

void   stck_destruct(stack *stck) {
    stck->stack = 0;
    stck->used = stck->size = 0;
    free(stck);
}

int    stck_push(stack *stck, int val) {
  if (stck->used == stck->size) {
    stck->size *= 2;
    stck->stack = (int *)realloc(stck->stack, stck->size * sizeof(int));
  }
  stck->stack[stck->used] = val;
  stck->used++;
  return 1;
}

int    stck_pop(stack *stck, int *val) {
  *val = stck->stack[stck->used];
  free(stck->stack);
  stck->used--;
  if (stck->used <= (stck->size)/4) {
    if (stck->size <=40) stck->size = 10;
    else stck->size /= 2;
    stck->stack = (int *)realloc(stck->stack, stck->size * sizeof(int));
  }

  return 1;
}

int main(){

    stack* test;

    test=stck_construct();

    int i; int out;
    for (i =1; i<=10; i++)
        stck_push(test, i);

    for (i =1; i<=10; i++)  {
        stck_pop(test,&out);
        printf("%i\n", out);
    }
    stck_destruct(test);
    return 0;
}

# endif

2 个答案:

答案 0 :(得分:5)

stack* stck_construct()中,您使用stck->而未先创建stck。实际上,它只是一个无处引用的指针。这肯定会产生分段错误。您将stack*与实际stack混淆(或者您可能忘了malloc整件事情:)

N.B:还有其他一些漫游我不提及的问题。如果您有兴趣,请参阅David's和Alexey的评论。

答案 1 :(得分:2)

Bugs annotated:

stack* stck_construct() {
    // stck is a pointer, you never initialize it to point to an existing object:
    stack *stck;
    // you dereference the invalid pointer with stck->stack:
    stck->stack = (int *)malloc(10 * sizeof(int));
    stck->used = 0;
    stck->size = 10;
    return stck;
}

void   stck_destruct(stack *stck) {
    stck->stack = 0;
    stck->used = stck->size = 0;
    // I thought you were assigning the pointer to the allocated memory to stck->stack,
    // and by now that pointer is 0 as you just did stck->stack = 0;
    free(stck);
}

  if (stck->used == stck->size) {
    stck->size *= 2;
    // if realloc() fails you end up with twice as big stck->size and
    // with stck->stack = NULL
    stck->stack = (int *)realloc(stck->stack, stck->size * sizeof(int));
  }

  // You first store the new element and then advance the index
  stck->stack[stck->used] = val;
  stck->used++;

  // But when you remove it you don't do the two operations in the reverse order:
  *val = stck->stack[stck->used];
  // and for some reason you additionally destroy all data
  free(stck->stack);
  stck->used--;

    // and then you realloc() using the invalid pointer (you just free()'d it!)
    stck->stack = (int *)realloc(stck->stack, stck->size * sizeof(int));