473,765 Members | 1,940 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(pt r, 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_ran ge("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_ran ge("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(voi d) {
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*option s(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.si ze());
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::solutio n;

//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(ar r, "arr", u8, 81, return 1, "exiting...
\n");
break;
case 1:
sIn = (char *)calloc(82, 1);
check_calloc(sI n, "sIn", char, 82, return 1, "exiting...
\n");
cin >sIn;
arr = parse(sIn);
check_calloc(ar r, "arr", u8, 81, return 1, "exiting...
\n");
break;
default:
fprintf(stderr, "usage:\n\tsudo ku 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(sI n, "sIn", char, 82, return 1, "exiting...\n") ;
fgets(sIn, 81, f);
arr = parse(sIn);
check_calloc(ar r, "arr", u8, 81, return 1, "exiting...\n") ;
solve:
sol = solver::solve(a rr);
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 2414
On Oct 1, 9:31 pm, andrey....@gmai l.com wrote:
On Oct 1, 8:01 pm, "Alf P. Steinbach" <al...@start.no wrote:

...
//get all available options for value val
vector<u8*optio ns(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!operato r new()
sudoku![std::vector allocate]
sudoku!std::vec tor::insert
sudoku!std::vec tor::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.no wrote:
* andrey....@gmai l.com:


On Oct 1, 9:31 pm, andrey....@gmai l.com wrote:
On Oct 1, 8:01 pm, "Alf P. Steinbach" <al...@start.no wrote:
...
//get all available options for value val
vector<u8*optio ns(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!operato r new()
sudoku![std::vector allocate]
sudoku!std::vec tor::insert
sudoku!std::vec tor::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
5665
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 for(int i = 0; i < 10; ++i) { #5 *ii++ = 4; #6 } #7 copy(vi.begin(), vi.end(), ostream_iterator<int>(cout, " "));
2
8696
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 vector, e.g: vector<int> x(10); vector<int>* p = &x; *p.resize( 5 ); cout << *p << endl;
12
1357
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
3521
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
1952
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 beyond the file. At some point, I tried to mend that behavior using feof() but without success. The functionality is not harmed, but this has started to bug me. What am I missing here? Sometimes being a code duffer is frustrating!! lol!!! The...
3
2146
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. Nevertheless the allocator produces "Segmentation fault (core dumped)". Is it possible to correct that allocator in order to avoid such behavior ------ foo.cpp ------
8
3208
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 need to change. Thanks. #include <malloc.h> #include <string.h>
6
5650
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. char temp; std::vector<unsigned charmmessage; while (!done){
11
2437
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
9566
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9393
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9946
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7371
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6646
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5272
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3921
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2800
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.