473,387 Members | 1,520 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

vector has segfault null dereference

code:

#include <iostream>
#include <vector>
#include <stdexcept>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>

using namespace std;

#ifdef _MSC_VER
#define inline __inline
#endif

typedef unsigned __int8 u8;
typedef signed __int8 s8;
typedef unsigned __int16 u16;

#define nullptr(T) (T *)0

#define check_calloc(ptr, ptrname, type, n, if_fail, if_fail_msg) \
if (ptr == nullptr(type)) {\
cerr << "calloc could not allocate " << ptrname << " [n=" << n <<
"], " << if_fail_msg; \
if_fail; \
}

template <typename T>
class array {
public:
size_t length;
array(size_t _length) {
data = new T[_length];
length = _length;
}
T& operator[](unsigned int n) {
if ((size_t)n >= length) {
cerr << "Array index out of range (n=" << n << ", length=" <<
length << "\"\n";
throw std::out_of_range("Array index out of range");
}
return data[n];
}
T& elem(unsigned int n) {
if ((size_t)n >= length) {
cerr << "Array index out of range (n=" << n << ", length=" <<
length << "\"\n";
throw std::out_of_range("Array index out of range");
}
return data[n];
}
~array() { delete[] data; }
private:
T* data;
};

class solver {
public:
solver() {
cells = (u16 *)calloc(81, 2);
zeroBit = (char *)calloc(11, 1);
}
//garbage collection
~solver() {
free(cells);
cells = (u16 *)0;
free(zeroBit);
zeroBit = (char *)0;
}
static u8 *solve(u8 *board) {
solver *s = encode(board);
solver *s_copy = s;
u8 *sol = nullptr(u8);
solution = false;
s = s->search();
if (solution) {
sol = s->decode();
delete s;
} else
delete s_copy;
return sol;
}
protected:
//data
u16 *cells;
//0th bit
char *zeroBit;
//is the puzzle solved
static bool solution;
//copy current solver
solver *duplicate(void) {
solver *dest = new solver();
u8 i;
for (i = 0; i < 81; i++) {
dest->cells[i] = cells[i];
dest->zeroBit[i] = zeroBit[i];
}
return dest;
}
//check zeroBit
inline bool checkBit(u8 i, char bit) {
u8 _byte = (u8)floor((i + 1) / 8.0);
return ((zeroBit[_byte] & (1 << (i % 8))) == bit) ? true : false;
}
//find most constrained position
u8 constrained(void) {
u8 max = 0x7f;
u8 maxp = 0x7f, i;
u8 j, v;

for (i = 0; i < 81; ++i) {
if (checkBit(i, 0)) {
v = 0;
for (j = 0; j < 9; ++j)
if (((1 << j) & cells[i]) != 0)
++v;
if (v >= max || max >= 0x7f) {
max = v;
maxp = i;
}
}
}
return maxp;
}
//get all available options for value val
array<u8*options(u16 val) {
vector<u8cc(0);;
array<u8*arr;
u8 i;
//find and add avialbale numbers
for (i = 0; i < 9; ++i)
if (((1 << i) & val) == 0)
cc.push_back(i + 1);
arr = new array<u8>(cc.size());
for (i = 0; i < arr->length; i++)
arr->elem(i) = cc[i];
return arr;
^ segfault null dereference at this line when vc++
does cleanup of vector before returning ^
}
//set value val in position pos, NOT-masking the other positions in
the group
void set(u8 pos, u8 val) {
//column
u8 x = pos % 9;
//row
u8 y = (u8)floor((pos * 1.0) / 9);
//zone column, row
u8 zx = (u8)floor((x * 1.0) / 3) * 3;
u8 zy = (u8)floor((y * 1.0) / 3) * 3;
//value bit
u16 add = 1 << ((u16)val - 1);
u8 k;
//NOT-mask the other positions in the group
for (k = 0; k < 9; ++k) {
//mask column
cells[x + k * 9] |= add;
//mask row
cells[k + y * 9] |= add;
//mask zone
cells[zx + (k % 3) + 9 * (zy + (u8)floor((k * 1.0) / 3))] |= add;
}
//unmask pos
cells[pos] = 0x1ff - add;
}
//sanity check
inline bool okay(void) {
u8 i;
for (i = 0; i < 81; ++i)
if (((cells[i] & 0x1ff) == 0x1ff) && checkBit(i, 0))
return false;
return true;
}
//check if solved
inline bool solved(void) {
u8 i;
for (i = 0; i < 81; ++i) {
if (checkBit(i, 0))
return false;
}
return true;
}
//search for solutions, return pointer to solution or null pointer
solver *search(void) {
u8 p;
array<u8*l;
u8 i;
solver *ns;
solver *ns_backup; //avoid memory leaks by backing up pointer
while (okay()) {
if (solved()) {
solution = true;
return this;
}
//start solving from most constrained position
p = constrained();
//no solution
if (p < 0)
return nullptr(solver);
//get all the available options for cell p
l = options(cells[p]);
//no solution
if (l->length < 1)
return nullptr(solver);
//try each option in cell p by recursing ourselves
//(i.e., (...(ns = this) ... = this))
for (i = 0; i < l->length; ++i) {
//recurse
ns = duplicate();
ns->set(p, l->elem(i));
ns_backup = ns; //avoid memory leaks
ns = ns->search();
//solution found, recurse back up
if (ns != nullptr(solver))
return ns;
else //solution not found, deallocate ns using backup
delete ns_backup;
}
//try first option
set(p, l->elem(0));
delete l;
}
//failed sanity check
return nullptr(solver);
}
//decode bitmask solution to numerical solution
u8 *decode(void) {
u8 *arr = (u8 *)calloc(81, sizeof(u8));
if (arr == nullptr(u8))
return arr;
u8 i;
u8 j;
for (i = 0; i < 81; ++i)
for (j = 0; j < 9; ++j)
if (((cells[i] | (u16)(1 << j)) == 0x1ff) &&
checkBit(i, 1)) {
arr[i] = j + 1;
break;
}
return arr;
}
static solver *encode(u8 *arr) {
solver *a = new solver();
u8 i;
for (i = 0; i < 81; ++i) {
/* MAKE SURE that the number is between 1 and 9,
inclusive so that the
* solver does NOT mask 0 because that would break
function isOK() and
* hence prevent the solver from reaching a solution.
*/
if (arr[i] >= 1 && arr[i] <= 9)
a->set(i, arr[i]);
}
return a;
}
};
bool solver::solution;

//pase sIng to array
u8 *parse (const char *str) {
u8 i;
u8 *arr = (u8 *)calloc(81, 1);
if (arr == nullptr(u8))
return nullptr(u8);
for (i = 0; i < 81; i++) {
if (str[i] 0x30 && str[i] <= 0x39) //'1'-'9'
arr[i] = str[i] - 0x30;
else
arr[i] = 1 << 7;
}
return arr;
}
//create sIng from array
char *arr_str(const u8 *arr) {
char *str = (char *)calloc(82, 1);
u16 i;
if (str == nullptr(char))
return nullptr(char);
for (i = 0; i < 81; i++)
if (arr[i] < 10)
str[i] = arr[i] + 0x30; //1-9
else
str[i] = 0x3f; //?
str[81] = '\0';
return str;
}

int main(int argc, char *argv[]) {
u8 *arr;
u8 *sol;
FILE *f;
char *sIn = nullptr(char);
switch (argc) {
case 2:
if (argv[1][0] < 0x31 || argv[1][0] 0x39)
goto from_file;
arr = parse(argv[1]);
check_calloc(arr, "arr", u8, 81, return 1, "exiting...
\n");
break;
case 1:
sIn = (char *)calloc(82, 1);
check_calloc(sIn, "sIn", char, 82, return 1, "exiting...
\n");
cin >sIn;
arr = parse(sIn);
check_calloc(arr, "arr", u8, 81, return 1, "exiting...
\n");
break;
default:
fprintf(stderr, "usage:\n\tsudoku input\n\tsudoku < input
\n");
return 1;
} //switch(argc)
goto solve;
from_file:
f = fopen(argv[1], "r");
sIn = (char *)calloc(82, 1);
check_calloc(sIn, "sIn", char, 82, return 1, "exiting...\n");
fgets(sIn, 81, f);
arr = parse(sIn);
check_calloc(arr, "arr", u8, 81, return 1, "exiting...\n");
solve:
sol = solver::solve(arr);
if (sol == nullptr(u8)) {
cout << "No solution found for puzzle "
<< (argc == 2 ? argv[1] : (sIn != nullptr(char)) ?
sIn : '\0') << endl;
return 0;
} else {
cout << "Solution for puzzle " << (argc == 2 ? argv[1] : (sIn !
= nullptr(char)) ? sIn : '\0')
<< " is " << arr_str(sol) << endl;
return 0;
}
}

Oct 1 '07 #1
2 2373
On Oct 1, 9:31 pm, andrey....@gmail.com wrote:
On Oct 1, 8:01 pm, "Alf P. Steinbach" <al...@start.nowrote:

...
//get all available options for value val
vector<u8*options(u16 val) {
vector<u8*cc = new vector<u8>();
According to my debugging, ^this^ line is throwing std::bad_alloc due
to a null pointer being returned from malloc. What is weird is that I
am allocating only 1 vector and I have 1 GB of ram so why is malloc
returning null?
Call trace:
[OS-dependent stuff]
C++ library!malloc()
C++ library!operator new()
sudoku![std::vector allocate]
sudoku!std::vector::insert
sudoku!std::vector::push_back
sudoku!solver::options
....
sudoku!main
....
u8 i;
//find and add avialbale numbers
for (i = 0; i < 9; ++i)
if (((1 << i) & val) == 0)
cc->push_back(i + 1);
return cc;
}
...
Oct 2 '07 #2
On Oct 1, 11:49 pm, "Alf P. Steinbach" <al...@start.nowrote:
* andrey....@gmail.com:


On Oct 1, 9:31 pm, andrey....@gmail.com wrote:
On Oct 1, 8:01 pm, "Alf P. Steinbach" <al...@start.nowrote:
...
//get all available options for value val
vector<u8*options(u16 val) {
vector<u8*cc = new vector<u8>();
According to my debugging, ^this^ line is throwing std::bad_alloc due
to a null pointer being returned from malloc. What is weird is that I
am allocating only 1 vector and I have 1 GB of ram so why is malloc
returning null?
Call trace:
[OS-dependent stuff]
C++ library!malloc()
C++ library!operator new()
sudoku![std::vector allocate]
sudoku!std::vector::insert
sudoku!std::vector::push_back
sudoku!solver::options
...
sudoku!main
...
u8 i;
//find and add avialbale numbers
for (i = 0; i < 9; ++i)
if (((1 << i) & val) == 0)
cc->push_back(i + 1);
return cc;
}
...

You have an infinite recursion in your search() function.

But the code has many other problems.

I suggest you start instead with removing all gotos, all raw arrays, all
calls to calloc and malloc and so on. One way to do that, which is what
I would prefer, is to copy your existing code to a backup (to look at),
than delete all contents of your file and start from scratch with an
empty main(). Remember to give yourself an electric shock every time
you even /think/ about reaching for goto or raw array or the like... :-)
The same thing happened when I tried to optimize my java code. How did
you catch the infinite recursion and do you know of a free static code
analyzer that can find infinite recursion?
Also, the java code used a raw array just fine.

Oct 2 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: john smith | last post by:
HI, when I try the following code, I get a segfault when compiled with VC.NET and g++ under cygwin. #1 vector<int> vi; #2 vector<int>::iterator ii = vi.begin(); #3 vi.reserve(10); #4 ...
2
by: Sean Dettrick | last post by:
Hi, Can anyone please tell me if the following is possible, and if so, what is the correct syntax? I'd like to resize a vector (and access other vector member functions) via a pointer to that...
12
by: Sims | last post by:
Hi, Here is the code that .NET does not seem to like, but as far as i can see it is valid C++ code. Am i wrong? .... // vector headers ....
40
by: Fatih Gey | last post by:
Hi, .. following causes a segfault. .. didn't know why ?! int main() { char name; strcpy (name, "ab8bc8cd8ed"); char cur;
10
by: name | last post by:
When I started testing the algorithms for my wrap program, I threw together this snippet of code, which works quite well. Except that it (predictably) segfaults at the end when it tries to go...
3
by: Alex Vinokur | last post by:
Compiler GNU g++ version 3.4.4 (cygming special) Custom allocator for vector (see below) checks a return value of 'operator new'. If that value is NULL, the allocator "allocates" no memory....
8
by: nobrow | last post by:
Okay ... Im out of practice. Is it not possible to have a 2D array where each column is of a different type, say an int and a struct*? The following seg faults for me and I cant figure out what I...
6
by: Bobrick | last post by:
Hi. Thanks to everyone who replied to my last post, it turns out it wasn't the line where I was trying to treat the variable in question as an array which was the problem, but the line above. ...
11
by: nandor.sieben | last post by:
I am trying to replace template < class T void set2vector (const set < T &s, vector < T &v) { typename set < T >::iterator it; for (it = s.begin (); it != s.end (); it++) { v.push_back (*it);...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.