c - 错误 "malloc: *** error for object 0x7b: pointer being freed was not allocated"可能是什么原因

标签 c malloc free runtime-error

我正在为一个类(class)编写这个程序。该程序是一个使用堆栈的简单括号检查器应用程序。在本例中,我使用静态数组来实现堆栈数据结构。该程序构建得很好,但我遇到了这个运行时错误,到目前为止还无法看出问题可能源于何处。

这里有一些信息,我确实明白问题可能是由于尝试释放未使用 malloc 分配的内存。但在下面的代码中,我看不出这种情况可能发生在哪里。

下面是使用静态数组的stack的接口(interface)实现代码。我还添加了堆栈接口(interface)代码以在堆栈上添加字符以及驱动程序以测试例程。

#include "stack.h"
#include "stdlib.h" /* malloc, free */
#include "stdio.h"

#define MAXSTACKSIZE 10

struct stack_record {
  generic_ptr base[MAXSTACKSIZE];
  generic_ptr * top;
};

unsigned int num_elements(stack * const p_S)
{
  unsigned int numels = ((*p_S)->top - (*p_S)->base);
  /*  return ((*p_S)->top - (*p_S)->base); */
  printf("number of elements in the stack is: %u\n", numels);
  return numels;
}
status init_stack(stack * const p_S)
{
  stack_record * record = (stack_record *)malloc(sizeof(stack_record));
  if(record == NULL) {
    return ERROR;
  }
  record->top = record->base;
  *p_S = record;
  return OK;
}
bool empty_stack(stack * const p_S)
{
  if(num_elements(p_S) == 0)
    {
      printf("stack is EMPTY!\n");
      return TRUE;
    }
  else
    {
      printf("stack NOT Empty!\n");
      return FALSE;
    }
}
status push(stack * const p_S, generic_ptr const data)
{
  if (num_elements(p_S) == MAXSTACKSIZE)
    return ERROR;

  *( (*p_S)->top ) = data;
  (*p_S)->top++;
   return OK;
}

status pop(stack * const p_S, generic_ptr * const p_data)
{
  if (empty_stack(p_S) == TRUE)
    return ERROR;
  *p_data = *((*p_S)->top);
  (*p_S)->top--;
  /*  ((*p_S)->top)--; */
  return OK;
}

status top(stack *const p_S, generic_ptr * const p_data)
{
   if (pop(p_S, p_data) == ERROR)
    return ERROR;

  return push(p_S, *p_data);
}

void destroy_stack(stack * const p_S, void (* const p_func_f)())
{
  if ((p_func_f) != NULL) {
    generic_ptr * curr;    
    for(curr = (*p_S)->top;
    curr != (*p_S)->base;
    ++curr)
          (*p_func_f)(*curr);
  }
  free(*p_S); /*free the dynamically allocated memory on the heap */
  *p_S = NULL;
 }

以下是字符的堆栈接口(interface)例程:

/*************************************************************************/
/* adapted from Esakov and Weiss, Section 5.2                            */
/*************************************************************************/

#include "char_stack.h"
#include "stdlib.h" /* malloc */
#include "stdio.h"
#define DEBUG 1 

status push_char(stack * const p_S, char const c)
{
  /*
   *     Push the character c onto the stack.
   */
  char * p_c = (char *) malloc(sizeof(char));

  if(p_c == NULL)
    return ERROR;
  *p_c = c;

  if(DEBUG)
  /* Debug code: begin */
  {
    printf("Character to PUSH on the stack: %c\n", *p_c);
  }
  /* Debug code: end */

  if (push(p_S, (generic_ptr)p_c) == ERROR) {
    if(DEBUG)
      printf("char_stack: push_char: failed to push the character on the stack!\n");
    free(p_c);
    return ERROR;
  }
  return OK;
}

status pop_char(stack * const p_S, char * const p_c)
{
  /*
   *     Pop the stack. Return the character in p_c.
   */

  generic_ptr p_data;

  if( pop(p_S, &p_data) == ERROR)
    return ERROR;

  *p_c = *((char*)p_data);

  if(DEBUG)
  /*Debug code: begin */
printf("char_stack.c::pop_char: Character to POP on the stack: %c\n", *p_c);

  /*Debug code: end */

   free(p_data);
   return OK;
}

status top_char(stack * const p_S, char * const p_c)
{
  /*
   *     Return the top character from the stack in p_c
   */
  generic_ptr p_data;

  if (top(p_S, &p_data) == ERROR)
    return ERROR;

  *p_c = *((char *)p_data); 
  return OK;
}

应用程序的驱动程序:

/**************************************************************************/
/* adapted from Esakov and Weiss, Section 5.2                             */
/**************************************************************************/

#include "stdio.h"
#include "stdlib.h"
#include "char_stack.h"

char matching_symbol(char const c)
{
  switch(c) {
    case '(': return ')';
    case ')': return '(';
    case '}': return '{';
    case '{': return '}';
    case '[': return ']';
    case ']': return '[';
  }
  return 0;
}

status consume_char(stack * const p_S, char input)
{
  switch (input) {
    case '(':
    case '{':  
    case '[':
      return push_char(p_S, input); 
    case ')':
    case '}':
    case ']':
      { 
        char c;    
        if (pop_char(p_S, &c) == ERROR || c != matching_symbol(input)) { 
          return ERROR;
        } else {
          return OK;
        }
      }
    default:
      return OK; 
  }
}

int main(int argc, char * argv[])
{

  if (argc == 1) {
    exit(EXIT_SUCCESS);
  }

  {
    stack S;

    init_stack(&S);

    {
      char *ptr;
      for (ptr = argv[1];
           *ptr != '\0' && consume_char(&S, *ptr) == OK;
           ++ptr); 
      if (*ptr == '\0' && empty_stack(&S)) { 

    destroy_stack(&S,free);
        exit(EXIT_SUCCESS);
      } else {
    destroy_stack(&S,free);
        exit(EXIT_FAILURE);
      }
    }
  }  

  exit(EXIT_SUCCESS);  
}

我想补充一点,在驱动程序中,我已经缩小了对销毁堆栈的调用是触发此问题的原因。但我已经审查了这段代码,并相信这段代码没问题,问题出在其他地方。

[编辑 1]:为了完整起见,我在调用这些函数的位置附加了驱动程序代码。 [编辑2]:添加了字符的堆栈接口(interface)例程。

最佳答案

错误消息告诉您,您将值 0x7b 传递给了 free。这么小的数字永远不会是从 malloc 返回的内存块的地址。所以,大致有以下三种可能:

  1. 您有一个完全未初始化的指针,恰好以 0x7b 结尾,并且您将其传递给 free
  2. 您从一个包含 0 的指针开始,将其递增 0x7b,然后将其传递给 free
  3. 您遇到了一些更有创意的内存损坏错误,该错误已将有效指针值替换为 0x7b。

最快的方法是在 valgrind 下运行你的程序,让它告诉你这一切发生在哪里。您还可以在 gdb 中到处放置断点,看看您会看到什么。

关于c - 错误 "malloc: *** error for object 0x7b: pointer being freed was not allocated"可能是什么原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12886591/

相关文章:

c - 客户端断开连接后,是否必须关闭服务器端的套接字?

c - 用20MHz晶振在C中做延时(初级)

在不使用 sizeof 的情况下计算结构的大小(以字节为单位)

c - 在 malloc 中使用 sizeof(void)

在 C 中调用 free()

c - 无法释放 C 中的 const 指针

c - 当你有字符串和双变量时如何扫描

混淆访问 malloc 内存(未初始化)

C:对于这个要求,有没有比 FIFO 队列实现更好的东西?

c - 在 C 中释放内存时出现段错误