Cygwin renders GDB useless - gdb

I'm currently running Cygwin on Windows in order to use GCC and avoid using Visual Studio and MinGW.
GCC works great, however GDB is not doing so well. GDB cannot detect a segmentation fault - you can see where this would be a huge problem. When running the default a.exe file produced by gcc with problematic code, the terminal outputs "Segmentation fault (core dumped)". That's fine, great. However when running this gcc -g (and possibly -O0) compiled program under gdb, this is my output.
Starting program: /home/Beo/a.exe
[New Thread 25968.0x6500]
[New Thread 25968.0x64fc]
[Inferior 1 (process 25968) exited normally]
It should be detecting a segmentation fault here. When I run -backtrace the program (I can't backtrace afterward because there's no stack according to gdb), it does show a segmentation fault, but gives me no information as to where that occurs. The output is this:
Starting program: /home/Beo/a.exe -backtrace
[New Thread 25696.0x1208]
[New Thread 25696.0x6570]
Program received signal SIGSEGV, Segmentation fault.
0x5c636972 in ?? ()
I have no idea why it's doing this, any ideas?
(I've tried increasing cygwin's memory limit. It doesn't fix anything.)
(I should also point out that this isn't specific to this program, gdb detects the error just fine on my Linux box)
TEST CODE:
/*Heaps*/
#include <stdio.h>
#define LEFT(i) ((2*(i)) + 1)
#define RIGHT(i) ((2*(i)) + 2)
#define PARENT(i) ((i)/2)
void buildheap(int heap[], int heapsize);
void max_heapify(int heap[], int heapsize, int index);
void swap(int *, int *);
int main(){
int testheap[] = {0, 3, 8, 4, 2, 1, 99, 33, 3, 1, 2, 9};
int size = sizeof(testheap) / sizeof(testheap[0]);
buildheap(testheap, size);
/*int i;
for(i = 0; i < size; i++)
printf("[%d]", testheap[i]);
putchar('\n'); */
return 0;
}
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
return;
}
void max_heapify(int heap[], int heapsize, int index){
int l = LEFT(index);
int r = RIGHT(index);
int largest = index;
if(/*l < heapsize &&*/ heap[l] > heap[largest])
largest = l;
if(/*r < heapsize && */heap[r] > heap[largest])
largest = r;
if(largest != index){
swap(&heap[largest], &heap[index]);
max_heapify(heap, heapsize, largest);
}
return;
}
void buildheap(int heap[], int heapsize){
int i = heapsize/2 - 1;
for(; i >= 0; i--)
max_heapify(heap, heapsize, i);
return;
}

Have you tried with application verifier running? I get this same problem with mingw, but having application verifier fixes it. It's from Microsoft's webpage. It's real easy to use, just start it up, pick your .exe, and it runs in the background.

Related

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.

Fatal error: iostream: No such file or directory in compiling C program using GCC

Why when I wan to compile the following multi thread merge sorting C program, I receive this error:
ap#sharifvm:~/forTHE04a$ gcc -g -Wall -o mer mer.c -lpthread
mer.c:4:20: fatal error: iostream: No such file or directory
#include <iostream>
^
compilation terminated.
ap#sharifvm:~/forTHE04a$ gcc -g -Wall -o mer mer.c -lpthread
mer.c:4:22: fatal error: iostream.h: No such file or directory
#include <iostream.h>
^
compilation terminated.
My program:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
using namespace std;
#define N 2 /* # of thread */
int a[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; /* target array */
/* structure for array index
* used to keep low/high end of sub arrays
*/
typedef struct Arr {
int low;
int high;
} ArrayIndex;
void merge(int low, int high)
{
int mid = (low+high)/2;
int left = low;
int right = mid+1;
int b[high-low+1];
int i, cur = 0;
while(left <= mid && right <= high) {
if (a[left] > a[right])
b[cur++] = a[right++];
else
b[cur++] = a[right++];
}
while(left <= mid) b[cur++] = a[left++];
while(right <= high) b[cur++] = a[left++];
for (i = 0; i < (high-low+1) ; i++) a[low+i] = b[i];
}
void * mergesort(void *a)
{
ArrayIndex *pa = (ArrayIndex *)a;
int mid = (pa->low + pa->high)/2;
ArrayIndex aIndex[N];
pthread_t thread[N];
aIndex[0].low = pa->low;
aIndex[0].high = mid;
aIndex[1].low = mid+1;
aIndex[1].high = pa->high;
if (pa->low >= pa->high) return 0;
int i;
for(i = 0; i < N; i++) pthread_create(&thread[i], NULL, mergesort, &aIndex[i]);
for(i = 0; i < N; i++) pthread_join(thread[i], NULL);
merge(pa->low, pa->high);
//pthread_exit(NULL);
return 0;
}
int main()
{
ArrayIndex ai;
ai.low = 0;
ai.high = sizeof(a)/sizeof(a[0])-1;
pthread_t thread;
pthread_create(&thread, NULL, mergesort, &ai);
pthread_join(thread, NULL);
int i;
for (i = 0; i < 10; i++) printf ("%d ", a[i]);
cout << endl;
return 0;
}
Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use a C++ compiler such as clang++ or g++ (and a .cpp file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99, C11 or C18 (eg. gcc -std=c99, clang -std=c18 etc)
Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.
Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;
C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>
Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
Out of the two options, printf("\n"); works the faster as I observed.
When used printf("\n"); in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.031s
user 0m0.030s
sys 0m0.030s
When used putchar('\n'); in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.047s
user 0m0.030s
sys 0m0.030s
Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)
I faced the same error : -
fatal error: iostream: No such file or directory
#include <iostream>
After some time I found that, I'm making a very very noob mistake here. Actually I was running my program file by giving the extension ".c" only.... :-(
So check whether you're saving your file with proper extension or not...
In this case, it'll be .cpp for C++ program file. So check that once and maybe you'll be good to go.
So now first check if you have downloaded the MinGW and have added it to the env variables
to check use g++ --version on your cmd/terminal
now if the squiggly lines still appear install the c++ Intellisense extension
you will mostly get an error in the c_cpp_properties.json file because the compiler path may not be correct
so all you have to do is put the correct path and the swiggly lines will dissappear

sigsegv error in aggregate method

Here is my code:
#include <cstdlib>
#include <stdio.h>
#define NUM_READINGS 3
int* readingsTotal;
int* readingsAverage;
int readingsIndex;
using namespace std;
void avgOf(int* toFindAvgOf, int size) {
int i;
for (i = 0; i < size; i++) {
// Add reading to total for each component.
readingsTotal[i] += toFindAvgOf[i];
// Once method has been iterated through n (NUM_READINGS) times:
if (readingsIndex == NUM_READINGS - 1) {
// Set the arithmetic mean.
readingsAverage[i] = readingsTotal[i] / NUM_READINGS;
// Reset the total.
readingsTotal[i] = 0;
}
}
readingsIndex++;
}
int iterate(int findAvgOf) {
int toFindAvgOf[] = {findAvgOf, 20, 30};
avgOf(toFindAvgOf, sizeof (toFindAvgOf));
return readingsAverage[0];
}
int main(int argc, char** argv) {
readingsTotal = (int []){0, 0, 0};
readingsAverage = (int []){0, 0, 0};
int i;
for (i = 0; i < 3; i++) {
int smthd = iterate(12 + i * 2);
printf("%d\n", smthd);
}
return 0;
}
When I run this in netbeans c/c++, it builds with now errors but when it executes it fails and prints:
RUN FAILED (exit value 1, total time: 86ms)
When I go into debug mode it also fails immediately and gives the SIGSEGV error. From reading online I'm guessing there is some issue with the way I am dereferencing a pointer. But I have no clue where exactly it is failing at. I am pretty new to c++ so any help would be great!
In C, the sizeof function returns the size of the object in bytes.
So when you say:
sizeof (toFindAvgOf)
That will return 12 (assuming an int on your system is 4-bytes) thus causing an index out of bounds condition in the avgOf function.
To get the length of the array:
sizeof(toFindAvgOf) / sizeof(int)

C++ segmentation fault badly detected by debugger

Below is beginning of my c++ program. It looks quite normal for me but when I run it I gets segmentation fault. This is what the debugger gives me:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004008d4 in main () at usu.cpp:12
12 cin >> n >> k;
But the errer isn't connected with this line of code becouse when I put "reutrn 1" before for loop programs ends normally. What could be wrong? I compiling my program using: g++ -ggdb3
#include <iostream>
#include <stdio.h>
#define MAX_N 1000000
#define MAX_K 1000000
#define MAX_IL_KROKOW 500000
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
char klocki[MAX_N+1];
int Przes_C[MAX_IL_KROKOW];//podaje następne c po c znajdującym się na pozycji i
int Ktore_b[MAX_N];//na podstawie indeksu b w klockach zwraca indeks w tablicy Przes_b
int Przes_b[MAX_N];//zwraca indeks b w klockach na podstawie występowania b
int poprz_c = -1;
int ilosc_b = 0;
int klocki_len = 0;
for(int i=0;i<n;i++)
{
klocki[i] = getchar();
return 1;
if(klocki[i] == 'b')
{
Przes_b[ilosc_b] = i;
Ktore_b[i] = ilosc_b;
ilosc_b++;
}
if(poprz_c != -1 && klocki[i] == 'c')
Przes_C[poprz_c] = i;
if(klocki[i] == 'c')
poprz_c = i;
klocki_len++;
}
klocki[klocki_len] = '\0';
It's likely youur array allocation fails which leads to undefined behaviour when you try to write something to the arrays.
char klocki[MAX_N+1];
int Przes_C[MAX_IL_KROKOW];
int Ktore_b[MAX_N];
int Przes_b[MAX_N];
These are massive arrays. There's only a fixed size of stack allocated per process. Created dynamic arrays using new.
You could also define the array variables as global variables outside the main function. Depends on your program (length) whether that makes sense.

segmentation fault while using gsl_rng_uniform

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)