0

So here is my issue, I have been trying to figure this out for the last 5 hours, I have a header file, a tester file, and a c source file. I would really like to understand what is happening and why so I can avoid the issue in the future. The header file declares the struct but does not define it:

typedef struct Stack *StackP;

and in my source file, Stack.c I have defined the stack:

struct Stack
{
  int top;
  int capacity;
  int count;
  ItemT items;
};

where ItemT is defined as char *

in the tester file, the call goes:

StackP stackPtr = newStack();

and what I have for my newStack function located in the c source file is:

StackP newStack(void) {
  struct Stack stack1;
  StackP stackPtr = &stack1;
  (stackPtr->items) = (ItemT)malloc(DEFAULT_CAPACITY*sizeof(ItemT));        

  (stackPtr->top) = -1;
  (stackPtr->capacity) = DEFAULT_CAPACITY;
  (stackPtr->count) = 0;    
  fprintf(stderr, "\nSuccesfully allocated memory to items...\n");

  return stackPtr;
}

now, my push function is:

void pushStack(StackP stackPtr, ItemT item) {           
  if ((stackPtr->count) == (stackPtr->capacity)) {
    fprintf(stderr, "\nERROR: Full stack.\n");
  }
  else {
    stackPtr->items = item;
    fprintf(stderr, "\nSuccessfully pushed %s on to the stack...\n", stackPtr->items);
    (stackPtr->items)++;
    (stackPtr->top)++;
    (stackPtr->count)++;
  }
}

My question is this: Have I don't something wrong in any of these blocks of code.

If I call a function that says:

return (stackPtr->count);

it will return a random set of numbers instead of 0, or 1. For instance, if I push 2 strings to the stack, instead of count being 2, count is 479622 or some other random long number. Why is this happening?

Again, I would like to know what I'm doing wrong and not just correct syntax because I really HAVE to understand this.

4

1 回答 1

7

该程序具有未定义的行为,因为它正在从函数返回局部变量的地址:

StackP newStack(void) {
  struct Stack stack1;
  StackP stackPtr = &stack1;

  return stackPtr;
}

stack1newStack退出时不再存在。stackPtr如果要在函数范围之外存在,则必须指向动态分配的内存:

StackP newStack(void) {
  struct Stack stack1;
  StackP stackPtr = malloc(sizeof(*stackPtr));
  if (stackPtr)
  {
  }

  return stackPtr;
}

请参阅是否强制转换 malloc 的结果?

于 2015-01-22T21:05:41.197 回答