1

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

它实际上在 gcc 中编译而没有警告,但是当我尝试运行它时会产生“分段错误”。我发现这可能与指针损坏有关,但我没有看到任何错误,如果有人可以为我指出,我会很高兴。

干杯

# 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
4

2 回答 2

5

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

注意:还有一些我没有提到的其他错误。如果您有兴趣,请参阅 David 和 Alexey 的评论。

于 2013-01-22T15:29:19.303 回答
2

错误注释:

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));
于 2013-01-22T15:41:03.733 回答