I implemented a Priority Queue and its sorted himself with using vector
`
void sortQueue() {
std::vector<double> orders;
while (front != -1) {
orders.push_back(this->deQueue());
}
sort(orders.begin(), orders.end(), [](double o1, double o2) { return o1 < o2; });
for (int i = 0; i < orders.size(); ++i) {
this->Queue::enQueue(orders.back());
}
}
but after all lines of the function are executed gives that error
free(): invalid pointer Signal: SIGABRT (Aborted) on new_allocator.h
explanation on debugger is
Program received signal SIGABRT, Aborted. 0x00007ffff788957c in ?? () from /lib/x86_64-linux-gnu/libc.so.6
Program terminated with signal SIGABRT, Aborted. The program no longer exists.
Related
I am trying to count the number of occurances of each letter in an string
why is Abort signal from abort(3) (SIGABRT) occurring in my code
following is my code implementation
void result()
{
string a,b,c;
cin>>a>>b>>c;
int x[26]={0},i,j;
for(i=0;i<a.size();i++)
{
j=a[i]-'a';
x[j]++;
}
cout<<"YES";
return;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
This is the relevant part (I think) of my source code
#include <iostream>
#include <cstdarg>
#include <cstring>
#include <cstdlib>
class Poly
{
private:
double *coefficients;
size_t degree;
inline double *cfp(size_t i);
public:
Poly();
Poly(size_t n, ...);
void Print() const;
~Poly();
};
Poly::Poly()
{
this->degree = 0;
this->coefficients = new double(1);
*(this->coefficients) = 1.;
}
Poly::Poly(size_t n, ...)
{
va_list coefs;
va_start(coefs, n);
this->degree = n;
n++;
register double *cfs = new double(n);
this->coefficients = cfs;
while (n--)
{
*cfs = va_arg(coefs, double);
cfs++;
}
va_end(coefs);
}
void Poly::Print() const
{
bool started = false;
double c = this->cf(0);
putchar('a');
std::cout << this->degree << '\n';
if (c != 0.)
{
std::cout << c;
started = true;
}
size_t N = this->degree;
for (size_t i = 1; i <= N; i++)
{
c = this->cf(i);
if (c != 0.)
{
if (!started)
started = true;
else
std::cout << ((c < 0.) ? " - " : " + ");
//printf(" + ");
std::cout << fabs(c) << " x^" << i;
//printf("%lf x^%lu", c, i);
}
}
printf("\n");
}
Poly::~Poly()
{
delete this->coefficients;
}
int main()
{
//printf("\n"); <- Uncommenting this line stops the error
Poly p1(7, 1., 3., -9., 2., 0., 8., -2., 6.);
p1.Print();
}
Right now, Print method has many printfs and couts. But when I uncomment the line from main, malloc brings segmentation fault at the first print or cout or even putchar from the 'Print` method. I cannot find any memory leaks there. Why does it happen and how to prevent it?
I am using gcc (g++) 9.3.0 on WSL Ubuntu. The program is compiled with the flags -lc -g.
gdb showed me this
malloc(): corrupted top size
Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig#entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
50 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) backtrace
#0 __GI_raise (sig=sig#entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1 0x00007ffff7c0f859 in __GI_abort () at abort.c:79
#2 0x00007ffff7c7a3ee in __libc_message (action=action#entry=do_abort, fmt=fmt#entry=0x7ffff7da4285 "%s\n")
at ../sysdeps/posix/libc_fatal.c:155
#3 0x00007ffff7c8247c in malloc_printerr (str=str#entry=0x7ffff7da2556 "malloc(): corrupted top size") at malloc.c:5347
#4 0x00007ffff7c8583a in _int_malloc (av=av#entry=0x7ffff7dd5b80 <main_arena>, bytes=bytes#entry=1024) at malloc.c:4107
#5 0x00007ffff7c872d4 in __GI___libc_malloc (bytes=1024) at malloc.c:3058
#6 0x00007ffff7c6ee84 in __GI__IO_file_doallocate (fp=0x7ffff7dd66a0 <_IO_2_1_stdout_>) at filedoalloc.c:101
#7 0x00007ffff7c7f050 in __GI__IO_doallocbuf (fp=fp#entry=0x7ffff7dd66a0 <_IO_2_1_stdout_>) at libioP.h:948
#8 0x00007ffff7c7e0b0 in _IO_new_file_overflow (f=0x7ffff7dd66a0 <_IO_2_1_stdout_>, ch=97) at fileops.c:745
--Type <RET> for more, q to quit, c to continue without paging--
#9 0x00007ffff7c73482 in putchar (c=97) at putchar.c:28
#10 0x0000555555555cfe in Poly::Print (this=0x7fffffffdb90) at polynomial_r.cpp:241
#11 0x0000555555555fd2 in main () at test.cpp:7
(gdb) info frame
Stack level 0, frame at 0x7fffffffd6f0:
rip = 0x7ffff7c3018b in __GI_raise (../sysdeps/unix/sysv/linux/raise.c:50); saved rip = 0x7ffff7c0f859
called by frame at 0x7fffffffd820
source language c.
Arglist at 0x7fffffffd5c8, args: sig=sig#entry=6
Locals at 0x7fffffffd5c8, Previous frame's sp is 0x7fffffffd6f0
Saved registers:
rip at 0x7fffffffd6e8
(gdb)
Looks like you corrupted your heap by writing past the end of your heap-allocation. I think your problem is here:
register double *cfs = new double(n);
Note that the above code allocates a single double set to value n, when I think what you wanted to do was allocate an array of n doubles. To do that you'd need to use brackets instead of parentheses:
register double *cfs = new double[n];
I was solving the climbing leaderboard problem in hackerrank but my function gives segmentation fault.
vector<int> climbingLeaderboard(vector<int> scores, vector<int> alice) {
vector<int> res,i;
auto ip= unique(scores.begin(),scores.begin()+scores.size());
scores.resize(distance(scores.begin(),ip));
for(int i =0;i<alice.size();++i)
{
int curr =0;
while(alice[i]<=scores[curr]&&curr<scores.size())
++curr;
if(alice[i]==scores[curr-1])
res[i]=curr-1;
else if(alice[i]>scores[curr])
res[i]=curr;
else if(curr>scores.size()-1)
res[i]=curr;
}
return res;
}
It gives the following error:
> Program terminated with signal SIGSEGV, Segmentation fault.
> #0 0x0000000000402a01 in climbingLeaderboard (scores=..., alice=...)
> at /usr/local/include/c++/8.3.0/bits/stl_vector.h:930 930 operator[](size_type __n) _GLIBCXX_NOEXCEPT
Firstly, res[i] is accessed without allocating any elements in res.
vector<int> res should be vector<int> res(alice.size()).
Secondly, scores[curr] may be accessed before checking if curr<scores.size().
while(alice[i]<=scores[curr]&&curr<scores.size())
++curr;
should be
while(curr<scores.size()&&alice[i]<=scores[curr])
++curr;
and
else if(alice[i]>scores[curr])
res[i]=curr;
else if(curr>scores.size()-1)
res[i]=curr;
should be
else if(curr>scores.size()-1)
res[i]=curr;
else if(alice[i]>scores[curr])
res[i]=curr;
I am trying to implement a thread interface class
I am having a problem with join() function, it gives me a segmentation fault
the output:
g++ threadInterface.cpp -lpthread
[murtraja#localhost src]$ ./a.out
Name: Thread # 0
Policy: FIFO
Scope: System
State: Detached
Name: my thread!
Policy: Round Robin
Scope: System
State: Joinable
Now running my thread!
Segmentation fault (core dumped)
What is interesting is that when I call gdb
and set a break at MyThread::run, the prime nos are printed
and I get a message that:
.......
48 is not prime
49 is not prime
0x000000000040141c in main ()
(gdb) s
Single stepping until exit from function main,
which has no line number information.
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7bc920a in pthread_join () from /lib64/libpthread.so.0
please refer the code and help me, i am new to threads. BTW, i've removed some code and kept only that is necessary
#include <iostream>
#include<pthread.h>
#include<stdio.h>
#include<cstring>
using namespace std;
class MyThread
{
int policy, state, scope;
char name[35];
char policyName[30];
char stateName[30];
char scopeName[30];
pthread_attr_t attrib;
pthread_t id;
static int count;
void setPrintables();
public:
MyThread(void);
MyThread(char*);
void setPolicy(int);
void setState(int);
void setScope(int);
void setName(char*);
void printDetails();
void loadDefaults();
void run(void *(*function)(void*));
void join();
};
int MyThread::count = 0;
MyThread::MyThread()
{
loadDefaults();
count++;
}
MyThread::MyThread(char* name)
{
loadDefaults();
strcpy(this->name, name);
count++;
}
void MyThread::loadDefaults()
{
pthread_attr_init(&attrib);
pthread_attr_setinheritsched(&attrib, PTHREAD_EXPLICIT_SCHED);
state = PTHREAD_CREATE_JOINABLE;
scope = PTHREAD_SCOPE_PROCESS;
policy = SCHED_OTHER;
sprintf(name, "Thread # %d", count);
}
void MyThread::join()
{
if(state == PTHREAD_CREATE_JOINABLE)
pthread_join(id, NULL);
}
void MyThread::run(void *(*function)(void*))
{
cout<<"Now running "<<name<<endl;
pthread_create(&id, &attrib, function, NULL);
//function(this);
}
void *printFactorials(void*)
{
for(int i=1; i<50; i++)
{
long fact = 1;
for(int j=i; j>=1; j--)
{
fact*=(long)j;
}
cout<<i<<"! = "<<fact<<endl;
}
}
void *printPrimes(void*)
{
for(int i=1; i<50; i++)
{
int c = 0;
for(int j=1; j<=i; j++)
{
if(!(i%j))
c++;
}
if(c==2)
cout<<i<<" is prime"<<endl;
else
cout<<i<<" is not prime"<<endl;
}
}
int main() {
char name[] = "my thread!";
MyThread t1, t2(name);
t1.setPolicy('F');
t1.setState('D');
t1.setScope('P');
t2.setPolicy('R');
t2.setState('J');
t2.setScope('P');
t1.printDetails();
cout<<endl;
t2.printDetails();
//t1.run(printFactorials);
//void* (*f)(void*) = printPrimes;
t2.run(printPrimes);
//t1.join();
t2.join();
return 0;
}
UPDATE:
Using pthread_create(&id, NULL, function, NULL);, gives no seg fault and everything works flawlessly.
The code looks good correct.
However you should be using the compiler option -pthread but just linking to the PThread library with the linker option -lpthread. (https://stackoverflow.com/a/1665110/694576)
I have a program that reads a matrix from a file and stores it in the variable basis_MP, which is an instance variable. Since the values read from the files are very big (don't fit in native datatypes), I use GMP for a higher precision. I print the values of the matrix where the file is stored and they are correct.
After reading the file, I also initialize some other auxiliary variables that also use GMP. I declared them as instance variables, because I don't want to allocate and free them on each call to other methods. As soon as the line of code that initializes the first of them is executed, I get a segmentation fault.
basis.h:
#ifndef BASIS_H
#define BASIS_H
#include <math.h>
#include <gmp.h>
using namespace std;
class Basis {
private:
int rank; //No. vectors in the basis (also called n)
int dimension; //Dimension of each vector in the basis (also called m)
mpz_t **basis_MP; //Matrix containing all the vectors in the basis
mpf_t aux_MP_f0;
mpf_t aux_MP_f1;
mpf_t aux_MP_f2;
public:
Basis(); //Empty constructor
Basis(char *filename); //Constructor from file
}
basis_MP is the variable where the matrix is sotred, while aux_MP_f0, aux_MP_f1, aux_MP_f2 are the 3 auxiliary variables. All of them use GMP for a higher precision. In the constructor Basis(char *filename) all of these variables are initialized and the matrix is read.
basis.cpp:
#include "basis.h"
Basis::Basis() // Empty constructor
{
}
Basis::Basis(char* filename) // Constructor from file
{
char delim[] = " \n[]";
ifstream stream;
stream.open(filename);
if(!stream) cerr << "File was not read" << endl;
stream.seekg (0, stream.end);
int length = stream.tellg();
stream.seekg (0, stream.beg);
char * buffer = new char [length];
char * number = new char [length];
std::cout << "Reading " << length << " characters... " << endl;
stream.read (buffer,length);
int count = 0;
for (int i = 0; i < length; i++){
if (buffer[i] == '\n') {
count++;
break;
}
if (buffer[i] == ' ') {
count++;
}
}
dimension = count;
rank = count;
basis_MP = (mpz_t**)malloc(rank*sizeof(mpz_t*));
for (int i = 0; i < rank; i++)
basis_MP[i] = (mpz_t*)malloc(dimension*sizeof(mpz_t));
number = strtok(buffer, delim);
for (int i = 0; i < rank; i++) {
for (int j = 0; j < dimension; j++) {
mpz_init_set_str(basis_MP[i][j], number, 10);
number = strtok(NULL, delim);
}
}
stream.close();
mpf_init2(aux_MP_f0, mpz_sizeinbase(basis_MP[0][0], 2));
mpf_init2(aux_MP_f1, mpz_sizeinbase(basis_MP[0][0], 2));
mpf_init2(aux_MP_f2, mpz_sizeinbase(basis_MP[0][0], 2));
delete buffer;
delete number;
}
The auxiliary variables are initialized with the precision of the first vector of the matrix. The segmentation fault occurs on this line: mpf_init2(aux_MP_f0, mpz_sizeinbase(basis_MP[0][0], 2));
main.cpp:
#include "basis.h"
int main (int argc, char **argv) {
Basis *b = new Basis(argv[1]);
}
The error I get is the following:
Program received signal SIGSEGV, Segmentation fault.
_int_malloc (av=0x7ffff7114760 <main_arena>, bytes=144) at malloc.c:3489
3489 malloc.c: No such file or directory.
Output of the backtrace from gdb:
(gdb) bt
#0 _int_malloc (av=0x7ffff7114760 <main_arena>, bytes=144) at malloc.c:3489
#1 0x00007ffff6dd92f0 in __GI___libc_malloc (bytes=144) at malloc.c:2891
#2 0x00007ffff7b71829 in __gmp_default_allocate () from /home/fcorreia/install/gmpxx/lib/libgmp.so.10
#3 0x00007ffff7b721db in __gmpf_init2 () from /home/fcorreia/install/gmpxx/lib/libgmp.so.10
#4 0x000000000040208f in Basis::Basis (this=0x607010, filename=0x7fffffffea8c "/home/project/dim10.txt") at src/basis.cpp:55
#5 0x000000000040517b in main (argc=2, argv=0x7fffffffe818) at src/main.cpp:4
I also tried replacing mpf_init2 by mpf_init and got the following error:
*** Error in `/home/project/a.out': malloc(): memory corruption: 0x0000000000608080 ***
Program received signal SIGABRT, Aborted.
0x00007ffff6d8ce37 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.
And the corresponding backtrace:
(gdb) bt
#0 0x00007ffff6d8ce37 in __GI_raise (sig=sig#entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#1 0x00007ffff6d8e528 in __GI_abort () at abort.c:89
#2 0x00007ffff6dceb04 in __libc_message (do_abort=1, fmt=fmt#entry=0x7ffff6ed7a80 "*** Error in `%s': %s: 0x%s ***\n") at ../sysdeps/posix/libc_fatal.c:175
#3 0x00007ffff6dd829b in malloc_printerr (ptr=0x608080, str=0x7ffff6ed3bda "malloc(): memory corruption", action=<optimized out>) at malloc.c:4996
#4 _int_malloc (av=0x7ffff7114760 <main_arena>, bytes=24) at malloc.c:3447
#5 0x00007ffff6dd92f0 in __GI___libc_malloc (bytes=24) at malloc.c:2891
#6 0x00007ffff7b71829 in __gmp_default_allocate () from /home/install/gmpxx/lib/libgmp.so.10
#7 0x00007ffff7b72190 in __gmpf_init () from /home/install/gmpxx/lib/libgmp.so.10
#8 0x00000000004020fc in Basis::Basis (this=0x608010, filename=0x7fffffffea8c "/home/project/dim10.txt") at src/basis.cpp:55
#9 0x0000000000405219 in main (argc=2, argv=0x7fffffffe818) at src/main.cpp:4
Somewhere the memory is being corrupted and I can't figure out where. Probably, I'm not using gmp correct. Does anyone have some hints?
Thanks