segmentation fault while using gsl_rng_uniform - c++

I'm writing a program that uses the GSL's random number generator, and I am getting a segmentation fault when I try to pass an instance of the random number generator to a function. Here is my source code:
int main(void)
{
gsl_rng *r;
int deck[52];
int count = 0;
r = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set(r, time(NULL));
// Initialize a custom deck
// code omitted...
// Perform trials
for (int j = 0; j < NUMTRIALS; j++) {
shuffle_two(r, deck);
if (deck[NUMCARDS-1] + deck[NUMCARDS-2] == 11)
count++;
}
// Report result
cout << fixed << setprecision(6) << count/static_cast<double>(NUMTRIALS);
cout << endl;
gsl_rng_free(r);
}
void shuffle_two(gsl_rng* r, int deck[])
{
double u;
int bottom, random;
int temp_card;
for (int i = 0; i < 2; i++) {
u = gsl_rng_uniform(r);
//code for shuffling goes here
}
}
Evidently the value of r is changing while the algorithm is running. When I do a backtrace, I get r as sometimes null, sometimes 0xa. I'm not sure why. I think it might have something to do with the const pointer argument to the gsl_rng_uniform function, as documented here.
Here is the output of the debugger:
Program received signal SIGSEGV, Segmentation fault.
gsl_rng_uniform (r=0x0) at ../gsl/gsl_rng.h:167
167 ../gsl/gsl_rng.h: No such file or directory.
in ../gsl/gsl_rng.h
(gdb) backtrace
#0 gsl_rng_uniform (r=0x0) at ../gsl/gsl_rng.h:167
#1 0x0000000000400d97 in shuffle_two (r=0x0, deck=0x7fffffffdfd0)
at blackjack.cpp:55
#2 0x0000000000400cad in main () at blackjack.cpp:33
(gdb)

Related

Getting an error: "Segmentation fault (Core Dumped)" on my program. Everything working otherwise. Why?

I'm getting an error "segmentation fault(core dumped)" for my program here, but everything in the program seems to be working fine. I understand what the error signifies I just cant identify what in my code is causing it. Any ideas?
#include <cmath> // for use of math functions
#include <iomanip> // for output display
#include "cosc1437_tk_1371133.h"
using namespace std;
//Global Constansts
const int ROWS = 3;
const int COLS = 10;
//Prototypes: None (other than defined in toolkit)
// MAIN program
int main()
{
// Hello Message
displayMessage("Hello. This program will demonstrate the use of 2D Arrays and mathematical operations.");
// Intialize and load arrays with flight information
int dArr[ROWS][COLS];
for (int i = 2; i < ROWS + 2; i++){
for (int j = 1; j < COLS + 1; j++) {
dArr[i][j] = pow(i, j);
cout << setw(8);
cout << dArr[i][j];
}
cout << "\n";
}
//Goodbye Message
displayMessage("Goodbye!");
}
for (int i = 2; i < ROWS + 2; i++){
for (int j = 1; j < COLS + 1; j++) {
dArr[i][j] = pow(i, j);
You set the max value of ‘i’ and ‘j’ to exceed ROWS and COLS, which you used to set the array dimension with.
Since max position in the array is 1 less than the value used:
int a[9]; // indexes 0 through 8.
So when you attempt to access a position of ROWS or COLS you exceed the array’s size. This translates into a segfault.

SIGSEGV __gnu_cxx::new_allocator<int>::construct<int, int const&> in Codeforces Round #660 Problem D

I have been working on a problem from CodeForces round #660 Problem D
My code is as follows::
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> child; //Array of b[i](parent) vs i(child)
vector<long long int> a; //We will update it later, and will be our subtree
vector<int> b,found;
void DFS(int index_ptr ,int *answer){
if(found[index_ptr] == 0){
found[index_ptr] = 1;
//Call childor
for(int i=0;i<child[index_ptr].size();i++){
DFS(child[index_ptr][i], answer);
}
//As we are traversing back just add the answer
*answer += a[index_ptr];
if(a[index_ptr] > 0){
a[b[index_ptr]] += a[index_ptr];
}
}
return;
}
int main()
{
int n,i,answer;
cin >> n;
a.clear();
a.resize(n);
b.clear();
b.resize(n);
found.clear();
found.resize(n);
for(i=0;i<n;i++){
cin >> a[i];
found[i] = 0;
}
vector<int> parent;
for(i=0;i<n;i++){
cin >> b[i];
if(b[i]==-1)
parent.push_back(i);
}
child.clear();
child.resize(n);
for (i=0;i<n;i++){
child[b[i]].push_back(i);
}
for(i=0;i<parent.size();i++){
DFS(i, &answer);
}
cout << answer << endl;
return 0;
}
But it returns segmentation fault
After running gdb it shows the following results::
Breakpoint 3, main () at flintTreasure_V2.cpp:54
54 child[b[i]].push_back(i);
(gdb) c
Continuing.
Program received signal SIGSEGV, Segmentation fault.
0x000055555555692d in __gnu_cxx::new_allocator<int>::construct<int, int const&>
(this=0x55555576e368, __p=0x4)
at /usr/include/c++/7/ext/new_allocator.h:136
136 { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
I did compile it with -Wall tag and it didn't show any warning that I should be concerned of
I never encounter this type of Segmentation fault before, I guess it has something to do with my vector allocation or usage
As a general answer: you are not doing any explicit allocations or deletions, so it is likely the problem stems from an out-of-bounds access to one of the vectors. If you use v.at(i) instead of v[i] to access the ith element of a vector v, an out-of-bounds access will throw an exception, rather than cause a segmentation fault (or worse).
More precisely to this code: you are accessing the vector within child at index b[i], but earlier it appears b[i]==-1 is a valid or expected input. My guess, without seeing the input data, is that you are attempting to push back a value on to the vector at child[-1], which is an out of bounds access.

vector as input to pthread_create

I passed a structure into pthread_create. One component of the structure is a vector data. the "data" push_back in a loop in each thread. When the size of the loop is small, the code runs correctly. When the loop is large. I got the following error message:
munmap_chunk(): invalid pointer
munmap_chunk(): invalid pointer
Aborted (core dumped)
I tried m<100, it works. When trying the m<1000, it shows the error.
// compile using: g++ parallel_2.C -o oo -lpthread
#include <iostream>
#include <cstdlib>
#include <vector>
#include <thread>
using namespace std;
const unsigned NUM_THREADS = std::thread::hardware_concurrency();
//
struct INPUT
{
int start;
int end;
vector<int> data;
};
//
void *Loop(void *param)
{
INPUT *in = (INPUT*)param;
int start = in->start;
int end = in->end;
cout<<" start: "<<start<<" end: "<<end<<endl;
//for(int m=0; m<100000000; m++)
for(int i = start;i < end;i++)
for(int m=0; m<1000; m++) {
in->data.push_back(i);
}
//pthread_exit(NULL);
}
//
int main ()
{
pthread_t threads[NUM_THREADS];
INPUT input[NUM_THREADS];
for( int i=0; i < NUM_THREADS; i++ ){
cout << "main() : creating thread, " << i << endl;
input[i].start = i*5;
input[i].end = input[i].start + 5;
int rc = pthread_create(&threads[i], NULL,
Loop, (void *)&input[i]);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
for(int i = 0; i<NUM_THREADS; i++)
cout<<"!! size of "<<i<<": "<<input[0].data.size()<<endl;
pthread_exit(NULL);
}
munmap_chunk(): invalid pointer
munmap_chunk(): invalid pointer
Aborted (core dumped)
In the specific case of this example (main() assumes that the threads are done and consults the modified structures), you have to join() a thread before accessing the structure it is modifying.
for(int i = 0; i<NUM_THREADS; i++)
{
pthread_join(threads[i], NULL);
cout<<"!! size of "<<i<<": "<<input[0].data.size()<<endl;
}
This way, you are certain it is done, and not modifying the structure any more.
The problem did not show up with very few iterations because the threads had probably (but nothing is certain) ended their task before your last loop in main() tried to access their structures.
By the way, you should consider using std::thread.
(https://en.cppreference.com/w/cpp/thread/thread/thread)

thread example, segmentation fault

I wrote a simple C++ code to find the minimal value of a vector, find below. It compiles both on VC++ and g++, but runs onto a segmentation fault on the latter. I cannot tell apart if my code contains an UB or the g++ contains a bug. Can someone identify any mistake in my code?
The segfault arises at thread::join().
some debugging info
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) where
#0 0x0000000000000000 in ?? ()
#1 0x00000000004688f7 in std::thread::join() ()
#2 0x0000000000000000 in ?? ()
(gdb) thread
[Current thread is 1 (Thread 0x7c6880 (LWP 24015))]
Here is the code
#include <iostream>
#include <random>
#include <thread>
#include <vector>
#include <algorithm>
using namespace std;
void find_min(vector<double>& x, double& min_val, int& min_id)
{
min_id = distance(x.begin(), min_element(x.begin(), x.end()));
min_val = x[min_id];
}
void find_part_min(vector<double>& x, vector<int>& min_ids, vector<double>& min_vals, int id)
{
int start_id = (x.size()*id) / min_vals.size();
int end_id = (x.size()*(id + 1)) / min_vals.size();
for (int i = start_id; i < end_id; ++i)
{
if (x[i] < min_vals[id])
{
min_ids[id] = i;
min_vals[id] = x[i];
}
}
}
int main()
{
// define variables
int Nthreads = 16;
vector<double> x(256 * 256);
int min_id = 0;
double min_val = 0;
// fill up vector with random content
mt19937 gen(0);
uniform_real_distribution<> dis(0, 1);
generate(x.begin(), x.end(), bind(dis,gen));
// find min serial
find_min(x, min_val, min_id);
cout << min_id << "\t" << min_val << endl;
// initilaize variables for parallel computing
vector<double> min_vals(Nthreads, numeric_limits<double>::infinity());
vector<int> min_ids(Nthreads, -1);
vector<thread> myThreads;
for (int id = 0; id < Nthreads; ++id) // define each thread
{
thread myThread(find_part_min, ref(x), ref(min_ids), ref(min_vals), id);
myThreads.push_back(move(myThread));
}
for (int id = 0; id < Nthreads; ++id)
myThreads[id].join(); // part-calculations are finished
// merging the results together
min_val = numeric_limits<double>::infinity();
min_id = -1;
for (int i = 0; i < Nthreads; ++i)
{
if (min_vals[i] < min_val)
{
min_val = min_vals[i];
min_id = min_ids[i];
}
}
cout << min_id << "\t" << min_val << endl;
return 0;
}
I looked into the Makefile, and -static was used without -whole-archive, which leads to problem under g++ according https://gcc.gnu.org/ml/gcc-help/2010-05/msg00029.html
It tells that if libstdc++ is configured without __thread support and linking against -lpthread is static, this can happen due to a libstdc++ bug.
You should use -pthread as option for every compilation phase with GCC (g++), rather than linking against -lpthread.
There's more stuff involved than simple linkage using that flag actually.

Why segmentation fault occurs in further iterations of brute force

I am trying to solve a puzzle again! this is the link: http://www.puzzleup.com/2015/puzzle/?9
my method requires vectors. Because I use this method:
I valued all the corners, and I track each iteration thrugh the end(15 th corner). I start from 1 and record all the corners I ve been through in the possibilities 2d array.
#include <iostream>
#include <vector>
#include <cmath>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
/*
possibilities will keep the possible combinations, routes like {1,4}{4,8}{8,7} etc till it arrives to 15
*/
vector< vector<int> > possibilities;
int cubes[15][6] = { {2,3,5,0,0,0}, {1,4,6,0,0,0}, {1,4,7,0,0,0}, {2,3,8,0,0,0}, {1,6,7,0,0,0}, {2,5,8,0,0,0}, {3,5,8,0,0,0}, {4,6,7,9,10,13}, {8,11,12,0,0,0}, {8,11,14,0,0,0}, {9,10,15,0,0,0}, {9,13,15,0,0,0}, {8,12,14,0,0,0}, {10,13,15,0,0,0}, {11,12,14,0,0,0} };
int counterSet, i, j, temp, counter, sizeOfVec ;
int routeCheck(int a, int b)
{
//
if(possibilities.size()!=0)
{
//
sizeOfVec = 0 ;
for(i=0; i<possibilities.size(); i++)
{
//
sizeOfVec += possibilities[i].size();
}
if(sizeOfVec!=0)
{
//
for(i=0; i< sizeOfVec; i++)
{
//
if((possibilities[i][0] == a && possibilities[i][1] == b) || (possibilities[i][0] == b && possibilities[i][1] == a))
{
//
return 0;
}
}
return 1;
}
else
{
//
return 1;
}
}
else
{
//
return 1;
}
}
int routeKeeper(int a, int b)
{
//
if(routeCheck(a,b) == 0)
{
//
return 0;
}
else if(routeCheck(a,b) == 1)
{
//
possibilities.push_back({a,b});
}
}
void createRouteMap(int start, int end)
{
//
temp = j;
for(j=0; j<6; j++)
{
//
cout << j << endl;
if(cubes[start-1][j]==0)
{
//
}
else if(cubes[start-1][j]==end) // if it is destination
{
//
counter+=1;
cout << "counter is: " <<counter << endl;
}
else if(routeCheck(start, cubes[start-1][j])==1)
{
//
routeKeeper(start, cubes[start-1][j]);
cout << "vector size is: " <<sizeOfVec << endl;
createRouteMap(cubes[start-1][j], end);
}
}
j=temp;
possibilities.erase(possibilities.end());
}
int main(int argc, char** argv) {
counter = 0;
createRouteMap(1, 15);
cout<< counter << endl;
system("pause");
return 0;
}
My all code is above shared. I use bruteforce to count all possible ways to 15 th corner. However, eventhough there is no compiling error, terminal constantly get crashed. When I execute in debug mode(I use Dev-C++ 5.11) I get this error:
Program Received signal SIGSEGV: Segmentation Fault
Of course I ve researched and found similar questions about my problem. But most of the suggestors pointed this was about the program trying to access a memory which is not belong to it. But the crazy thing is, I actually access all the memory, you can try in any editor, it runs first 3 iterations and use all the functions and variables. Output is like this:
Why is this happening? I would apreciate any suggestion and direction. Thanks.
This part of code seems strange.
sizeOfVec = 0 ;
for(i=0; i<possibilities.size(); i++)
{
//
sizeOfVec += possibilities[i].size();
}
if(sizeOfVec!=0)
{
//
for(i=0; i< sizeOfVec; i++)
{
//
if((possibilities[i][0]
sizeOfVec is used to index the vector possibilities but it count the total size of the vectors which are possibilities elements.
Many would suggest you to use a debugger for this.