最近在CentOS用C++读数据,数据量挺大,而且是用的各种指针就出现了各种内存错误。调试的时候也是调试了很久,现将错误记录一下
出现munmap_chunk():invalid pointer的可能原因
一般来说,出现此类错误是在free的时候
(1)free的地址不是动态分配的地址
(2)动态分配的地址被修改过(对修改后的地址访问出问题)
我遇到的问题
描述:再分配内存不足。。。读取数据的时候是对结构体进行操作,且读取数据的程序需要配一定的环境,几千行的代码,不便于调试。故模仿当时所犯的错误,写了个小程序更直观一些。
/* * =============================================================================== * * Filename: Test.cc * * Description: This is a test program, to imaitate the read_data program. * * Using malloc init a struct array,the init size is n , when the size * * greater than n,we should use realloc function to expand the space. * * * Version : 1.0 * * Creted: 04/10/2016 11:57 * * Cretify: none * * Cretify time:none * * Compiler: gcc * * Author: XIU * * ============================================================================== */ #include#include using namespace std; struct Data { int index; }; void test( int all_data ) { int n = 100; struct Data * s_data = ( Data* ) malloc( sizeof(Data) * n ); for( int i = 0; i < all_data; i++ ) { if( i >= n ) { s_data = ( Data* ) realloc( s_data, (n+1) ); n++; } s_data[i].index = i; } for( int i = 0; i < all_data; i++ ) { cout << s_data[i].index << "\t"; } free( s_data ); } int main() { test( 200 ); return 0; }