如何找到错误: *** './a.out' 中的错误: free(): 无效的下一个大小 (快速): 0x09767150 ***

How can I locate error: *** Error in `./a.out': free(): invalid next size (fast): 0x09767150 ***

本文关键字:错误 快速 0x09767150 无效 下一个 out 何找 free      更新时间:2023-10-16

main.cpp和grid.h编译成功。当我在调整网格大小后使用fill函数时,就会出现这个问题。这将在运行程序后产生一个错误:

*错误在' ./a。out': free():无效的下一个大小(快速):0x0871d150 *

main.cpp

#include "grid.h"
#include <cstdlib>
#if 1
    #define log(x) std::cout << x << std::endl;
#else
    #define log(x) 
#endif  
#ifdef _GLIBCXX_CSTDLIB
    #define clear system("clear");
    #define reset system("reset");
#else
    #define clear
    #define reset
#endif
std::pair<const int, const int> LARGE  = std::make_pair(8,8);
std::pair<const int, const int> MEDIUM = std::make_pair(6,6);
std::pair<const int, const int> SMALL  = std::make_pair(4,4); 

int main(){
    clear
    grid<char> a(LARGE,'#');
    grid<int>  b(4,5,   9 );
    a.resize(4,8);
    b.resize(MEDIUM);
    b.fill(8);
    log(a);
    log(b);
    return 0;
}

grid.h

#ifndef GRID_H
#define GRID_H
#include <iostream>
#include <vector>
template<typename type>
class grid{
    public://Functions
        grid(std::pair<const type, const type> dimension, type filler = 0) : rows(dimension.first), cols(dimension.second){
                matrix.assign(rows, std::vector<type>(cols, filler));
        };
        grid(const int _rows, const int _cols, type filler = 0) : rows(_rows), cols(_cols){
                matrix.assign(rows, std::vector<type>(cols, filler));
        };
        void resize(std::pair<const type, const type> dimension){
            rows = dimension.first, cols = dimension.second;
            matrix.resize(rows, std::vector<type>(cols));
        };
        void resize(const int _rows, const int _cols){
            rows = _rows, cols = _cols;
            matrix.resize(rows, std::vector<type>(cols));
        };
        void fill(type filler){
            for(int r = 0; r < rows; r++){
                for(int c = 0; c < cols; c++){
                    matrix[r][c] = filler;
                }
            }
        };
    public://Operators
        friend std::ostream& operator<<(std::ostream& out, grid& g){
            for(int r = 0; r < g.rows; r++){
                for(int c = 0; c < g.cols; c++){
                    out << g.matrix[r][c];
                }out << std::endl;
            }return out;
        };
        //Variables
        std::vector<std::vector<type>> matrix;
        int  rows;
        int  cols;
};
#endif//GRID_H
控制台输出

dylan@Aspire-one:~$ ./a.out
########
########
########
########
888888
888888
888888
888888
888888
888888
*** Error in `./a.out': free(): invalid next size (fast): 0x09767150 ***
Aborted (core dumped)
dylan@Aspire-one:~$ 

Error in './a.out': free(): invalid next size (fast): 0x0871d150

这个错误总是意味着你的程序损坏了它的堆(比如写过了堆分配缓冲区的末尾)。

标准的方法是在Valgrind下运行你的程序,它会直接指出问题所在。

地址消毒器(gcc -fsanitize=address -g ...)是另一个查找此问题的标准工具。

您的调整大小方法不正确。如果已经有N行并将大小调整为X行,则任何现有行都不会更改为新的列大小。当你使用它们时,你就失败了。