vendredi 27 mars 2015

This cpp code crash. Everytime I input a string of length 4, malloc in vector fails


I am using this program to store the values I input in the nxn matrix.


The first input is number of test cases. The second is the value of n. So I create a n*n matrix. Then I input the values for each row Ex: .... The input is always a combination of '.' or '#'.


Here is the code I am using:



#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdio.h>

// Calculate the offset of the nth column in the array
#define COL(val, R, C) (R*val)+C ? (R*val)+C:0


class matrix {
public:
int size; // value of n
int **row;
int *col;

public:
explicit matrix(int temp);
class matrix* valid_blocks(int *row, int **column); // For current pos find alid moves.
};

matrix::matrix(int val) {
size = val;
row = new int* [val];
col = new int[val*val];
// Now assign the row values in the row.
// Below code assigns a continuous block of data and splits it up for nxn matrix
// helps improve performance.
row[0]= &col[0];
for (int temp = 1; temp < (val); temp++) {
row[temp] = &col[temp*val];
}
for (int temp = 0; temp < val; temp++) {
for (int temp1 = 0; temp1 < val; temp1++) {
row[temp][COL(val, temp, temp1)] = 0;
}
}
}

int main() {
// Read the data
int total_test = 0;
int tmp, val = 0;
std::string tmp_s;

std::cin >> total_test;
// RUn it total_test number of time
for (; total_test; total_test--) {
std::cin >> val;
matrix path = matrix(val);
// Parse input
for (int row = val; row; row--) {
std::cin >> tmp_s;
std::vector<char> chars(tmp_s.begin(), tmp_s.end());
for(int col = val-1; col >= 0; col--) {
if (chars[col] == '#')
path.row[row][COL(val, row, col)] = -1;
}
}

}
return 0;
}


I run this program and everytime I give the input string to read as "...." this program crashes. I know the exact line where this occurs..


Its either cin >> tmp_s; (I am pretty sure think this is not the line) Its this line: std::vector chars(tmp_s.begin(), tmp_s.end());


The GDB has this to say! Can anyone help me with this? Thanks.



(gdb) s
57 std::cin >> tmp_s;
(gdb)
....
a.out: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.

Program received signal SIGABRT, Aborted.
0x00007ffff7531cc9 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56 ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb)


Thanks! :)




Aucun commentaire:

Enregistrer un commentaire