push_back a pointer of object results in segfault - c++

The following code is to move the "non-overlapping" TablePath from vector v to vector u. I am encountering segmentaion fault at the line "u.push_back(*it1);". I didn't copy the object(but instead only copy the pointer of the object) so I believe the problem doesn't lie in copying constructor. Can you give some hints on why segfault is occuring ?
#include <iostream>
#include <vector>
using namespace std;
class TablePath
{
private:
int source;
int destination;
public:
TablePath(int,int);
~TablePath();
int overlap(TablePath*);
void toString();
TablePath(const TablePath& that) : source(that.source), destination(that.destination)
{
}
};
TablePath::TablePath(int source=0,int destination=0)
{
this->source = source;
this->destination = destination;
}
int TablePath::overlap(TablePath* thatTablePath)
{
if (this->source >= thatTablePath->source and this->source <= thatTablePath->destination)
return 1;
else if (this->destination >= thatTablePath->source and this->destination <= thatTablePath->destination)
return 1;
else if (thatTablePath->source >= this->source and thatTablePath->source <= this->destination)
return 1;
else if (thatTablePath->destination >= this->source and thatTablePath->destination <= this->destination)
return 1;
else
return 0;
}
void TablePath::toString()
{
cout << this->source << " " << this->destination << endl;
}
int main()
{
int numofTests;
cin >> numofTests;
while(numofTests > 0)
{
int numofMoves;
vector<TablePath *> v;
cin >> numofMoves;
for (int i=0;i<numofMoves;i++)
{
int source,destination;
cin >> source >> destination;
TablePath* MyTablePath = new TablePath(source,destination);
v.push_back(MyTablePath);
}
vector<TablePath *> u;
vector<TablePath *>::iterator it1 = v.begin();
u.push_back(*it1);
v.erase(v.begin());
for(vector<TablePath *>::iterator it1 = v.begin(); it1 != v.end(); ++it1)
{
for(vector<TablePath *>::iterator it2 = u.begin(); it2 != u.end(); ++it2)
{
if ((*it1)->overlap((*it2)))
{
u.push_back(*it1);
}
}
}
cout << u.size() * 10;
v.erase(v.begin(),v.end());
u.erase(u.begin(),u.end());
numofTests--;
}
}
The following is the output I get from valgrind:
frank#frank-vm:~$ valgrind --tool=memcheck ./tablepath
==6172== Memcheck, a memory error detector
==6172== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==6172== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==6172== Command: ./tablepath
==6172==
1
3
10
20
15 30
20 50
==6172== Invalid read of size 4
==6172== at 0x8048BB0: main (in /home/frank/tablepath)
==6172== Address 0x4320184 is 0 bytes after a block of size 4 free'd
==6172== at 0x402ACFC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==6172== by 0x8049616: __gnu_cxx::new_allocator<TablePath*>::deallocate(TablePath**, unsigned int) (in /home/frank/tablepath)
==6172== by 0x80493E8: std::_Vector_base<TablePath*, std::allocator<TablePath*> >::_M_deallocate(TablePath**, unsigned int) (in /home/frank/tablepath)
==6172== by 0x8049230: std::vector<TablePath*, std::allocator<TablePath*> >::_M_insert_aux(__gnu_cxx::__normal_iterator<TablePath**, std::vector<TablePath*, std::allocator<TablePath*> > >, TablePath* const&) (in /home/frank/tablepath)
==6172== by 0x8048E00: std::vector<TablePath*, std::allocator<TablePath*> >::push_back(TablePath* const&) (in /home/frank/tablepath)
==6172== by 0x8048BED: main (in /home/frank/tablepath)
==6172==
==6172== Invalid read of size 4
==6172== at 0x8048965: TablePath::overlap(TablePath*) (in /home/frank/tablepath)
==6172== by 0x8048BCA: main (in /home/frank/tablepath)
==6172== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==6172==
==6172==
==6172== Process terminating with default action of signal 11 (SIGSEGV)
==6172== Access not within mapped region at address 0x0
==6172== at 0x8048965: TablePath::overlap(TablePath*) (in /home/frank/tablepath)
==6172== by 0x8048BCA: main (in /home/frank/tablepath)
==6172== If you believe this happened as a result of a stack
==6172== overflow in your program's main thread (unlikely but
==6172== possible), you can try to increase the size of the
==6172== main thread stack using the --main-stacksize= flag.
==6172== The main thread stack size used in this run was 8388608.
==6172==
==6172== HEAP SUMMARY:
==6172== in use at exit: 48 bytes in 5 blocks
==6172== total heap usage: 8 allocs, 3 frees, 64 bytes allocated
==6172==
==6172== LEAK SUMMARY:
==6172== definitely lost: 0 bytes in 0 blocks
==6172== indirectly lost: 0 bytes in 0 blocks
==6172== possibly lost: 0 bytes in 0 blocks
==6172== still reachable: 48 bytes in 5 blocks
==6172== suppressed: 0 bytes in 0 blocks
==6172== Rerun with --leak-check=full to see details of leaked memory
==6172==
==6172== For counts of detected and suppressed errors, rerun with: -v
==6172== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)

std::vector<T>::push_back is (usually) allowed to invalidate all iterators associated with the vector object. So after you do:
u.push_back(*it1);
it is not safe to continue the inner for loop with ++it2.
You could use an index for the inner loop instead. Or, break out of the inner loop right after doing the push_back, if you don't really want multiple copies of the same TablePath* pointer in u.

Related

C++ valgrind error message segmentation fault

I'm new to C++ and I'm trying to write an enigma machine simulator. I know I've done something funky with my pointers and I've run it through Valgrind, but I'm not sure what the error messages mean and where to begin fixing it? (What does suppressed mean in the leak summary?)
Here's part of the code where each component is created and where the error occurs.
Enigma::Enigma(int argc, char** argv){
errorCode = NO_ERROR;
plugboard = NULL;
*rotor = NULL; //WHERE THE ERROR OCCURS
reflector = NULL;
rotorCount = 0;
//first check how many rotors there are
if (argc >= 5)
rotorCount = argc - 4;
if (argc <= 4)
errorCode = INSUFFICIENT_NUMBER_OF_PARAMETERS;
//pass files into each component and check if well-formed
if (errorCode == NO_ERROR){
plugboard = new Plugboard(argv[1]);
errorCode = plugboard -> errorCode;
if (errorCode == NO_ERROR){
cout << "Plugboard configuration loaded successfully" << endl;
reflector = new Reflector(argv[2]);
errorCode = reflector -> errorCode;
if (errorCode == NO_ERROR){
cout << "Reflector configuration loaded successfully" << endl;
rotor = new Rotor*[rotorCount];
size_t i = 0;
while (i < rotorCount && errorCode == NO_ERROR) {
rotor[i] = new Rotor (argv[i+3]);
i++;
errorCode = rotor[i]-> errorCode;
//destructor if rotor loading was unsuccessful
if (errorCode != NO_ERROR){
for (int j=0; j<=i; j++)
delete rotor[j];
delete [] rotor;
Here's the Valgrind error message:
reflectors/I.rf rotors/I.rot rotors/II.rot rotors/III.rot rotors/I.pos
==68943== Memcheck, a memory error detector
==68943== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==68943== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==68943== Command: ./enigma plugboards/I.pb reflectors/I.rf rotors/I.rot rotors/II.rot rotors/III.rot rotors/I.pos
==68943==
--68943-- run: /usr/bin/dsymutil "./enigma"
==68943== Use of uninitialised value of size 8
==68943== at 0x100002598: Enigma::Enigma(int, char**) (enigma.cpp:17)
==68943== by 0x100002F92: Enigma::Enigma(int, char**) (enigma.cpp:12)
==68943== by 0x100000862: main (main.cpp:18)
==68943== Uninitialised value was created by a stack allocation
==68943== at 0x1000007D4: main (main.cpp:11)
==68943==
==68943== Invalid write of size 8
==68943== at 0x100002598: Enigma::Enigma(int, char**) (enigma.cpp:17)
==68943== by 0x100002F92: Enigma::Enigma(int, char**) (enigma.cpp:12)
==68943== by 0x100000862: main (main.cpp:18)
==68943== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==68943==
==68943==
==68943== Process terminating with default action of signal 11 (SIGSEGV)
==68943== Access not within mapped region at address 0x0
==68943== at 0x100002598: Enigma::Enigma(int, char**) (enigma.cpp:17)
==68943== by 0x100002F92: Enigma::Enigma(int, char**) (enigma.cpp:12)
==68943== by 0x100000862: main (main.cpp:18)
==68943== If you believe this happened as a result of a stack
==68943== overflow in your program's main thread (unlikely but
==68943== possible), you can try to increase the size of the
==68943== main thread stack using the --main-stacksize= flag.
==68943== The main thread stack size used in this run was 10022912.
==68943==
==68943== HEAP SUMMARY:
==68943== in use at exit: 18,685 bytes in 166 blocks
==68943== total heap usage: 187 allocs, 21 frees, 27,133 bytes allocated
==68943==
==68943== LEAK SUMMARY:
==68943== definitely lost: 0 bytes in 0 blocks
==68943== indirectly lost: 0 bytes in 0 blocks
==68943== possibly lost: 72 bytes in 3 blocks
==68943== still reachable: 200 bytes in 6 blocks
==68943== suppressed: 18,413 bytes in 157 blocks
==68943== Rerun with --leak-check=full to see details of leaked memory
==68943==
==68943== For counts of detected and suppressed errors, rerun with: -v
==68943== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 1 from 1)
Segmentation fault: 11
Thanks
Maybe you should take a look at: How do pointer to pointers work in C?
Basically, I see that rotor is a pointer to pointer or possibly an array of pointers (since you initialize *rotor to NULL and later also set rotor[i] = new Rotor).
Make sure you've initialized rotor properly. Is it pointing to a valid object? If not, you cannot expect *rotort = NULL /* or whatever value */; to work.
Basically suppressed means the memory leaks outside of your code in shared libraries.And *rotor = NULL,but it doesn't point to any valid object..

Seg Fault using stacks and queues

I am new to using stacks and queues and I am having memory problems. Could you give me a little insight in what I am doing wrong? This is supposed to be an implementation of a war game using stacks and queues.
#ifndef WAR_H
#define WAR_H
/*
This runWar function runs a game of war between 2 automated players
and returns the number of rounds (both put a card down
once per round) until someone won. An integer is given
as an upper limit to how many rounds a game can go on for.
*/
#include <iostream>
#include <stdlib.h>
#include <stdexcept>
#include <stack>
#include <queue>
#include "deck.h"
using namespace std;
int decide(Card, Card, unsigned int&);
int runWar(unsigned int limit)
{
Deck d;
queue<Card> p1;
queue<Card> p2;
while(d.size() != 0)
{
p1.push(d.getTopCard());
if(d.size() != 0)
{
p2.push(d.getTopCard());
}
}
bool winner = false; //checks if anyone won
unsigned int roundcount = 0; //checks number of comparisons
while(roundcount<limit && winner == false)
{
Card one = p1.front();
Card two = p2.front();
p1.pop();
p2.pop();
if(one.getRank() > two.getRank())
{
roundcount++;
p1.push(one);
p1.push(two);
}
else if(one.getRank() < two.getRank())
{
roundcount++;
p2.push(one);
p2.push(two);
}
else
{
stack<Card> pile;
//3 cards off the top each
bool war_done = false;
while(war_done == false)
{
for(unsigned int w=0; w<3; w++)
{
pile.push(p1.front());
pile.push(p2.front());
p1.pop();
p2.pop();
}
Card p11 = p1.front();
Card p22 = p2.front();
pile.push(p11);
pile.push(p22);
p1.pop();
p2.pop();
if(p11.getRank() > p22.getRank())
{
roundcount++;
while(!(pile.empty()))
{
p1.push(pile.top());
pile.pop();
}
p1.push(one);
p1.push(two);
war_done = true;
}
else if(p11.getRank() > p22.getRank())
{
roundcount++;
while(!(pile.empty()))
{
p2.push(pile.top());
pile.pop();
}
p2.push(one);
p2.push(two);
war_done = true;
}
}
if(p1.empty() || p2.empty())
{
winner = true;
}
}
}
return roundcount;
}
#endif
int main()
{
for(unsigned int i=0; i<19; i++)
{
cout<<runWar(1000)<<endl;
}
return 0;
}
My card and deck classes work find. getTopCard() is basically a pop that returns the top card. getRank() says if it is a 2-Ace. Also, the int main() is in the driver.cpp file.
Valgrind Output:
==3942== Memcheck, a memory error detector
==3942== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3942== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==3942== Command: ./doWar
==3942==
==3942== Conditional jump or move depends on uninitialised value(s)
==3942== at 0x4023BA: runWar(unsigned int) (war.h:77)
==3942== by 0x4016F6: main (doWar.cpp:18)
==3942==
==3942== Conditional jump or move depends on uninitialised value(s)
==3942== at 0x40201B: runWar(unsigned int) (war.h:45)
==3942== by 0x4016F6: main (doWar.cpp:18)
==3942==
==3942== Use of uninitialised value of size 8
==3942== at 0x401FCD: runWar(unsigned int) (war.h:41)
==3942== by 0x4016F6: main (doWar.cpp:18)
==3942==
==3942== Invalid read of size 4
==3942== at 0x401FCD: runWar(unsigned int) (war.h:41)
==3942== by 0x4016F6: main (doWar.cpp:18)
==3942== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==3942==
==3942==
==3942== Process terminating with default action of signal 11 (SIGSEGV)
==3942== Access not within mapped region at address 0x0
==3942== at 0x401FCD: runWar(unsigned int) (war.h:41)
==3942== by 0x4016F6: main (doWar.cpp:18)
==3942== If you believe this happened as a result of a stack
==3942== overflow in your program's main thread (unlikely but
==3942== possible), you can try to increase the size of the
==3942== main thread stack using the --main-stacksize= flag.
==3942== The main thread stack size used in this run was 8388608.
==3942==
==3942== HEAP SUMMARY:
==3942== in use at exit: 1,728 bytes in 6 blocks
==3942== total heap usage: 33 allocs, 27 frees, 8,952 bytes allocated
==3942==
==3942== LEAK SUMMARY:
==3942== definitely lost: 0 bytes in 0 blocks
==3942== indirectly lost: 0 bytes in 0 blocks
==3942== possibly lost: 0 bytes in 0 blocks
==3942== still reachable: 1,728 bytes in 6 blocks
==3942== suppressed: 0 bytes in 0 blocks
==3942== Rerun with --leak-check=full to see details of leaked memory
==3942==
==3942== For counts of detected and suppressed errors, rerun with: -v
==3942== Use --track-origins=yes to see where uninitialised values come from
==3942== ERROR SUMMARY: 31 errors from 4 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
Before every 'pop()' check wheather it is empty or not like
If(!p1.empty()){
p1.pop();
}

can't find error Invalid read of size 4 valgrind

I have implemented multitask application in c++. Producer push on queue, and consumer get elements from queue. Sometimes my application crashed. Could someone help me with this problem. sf
Valgrind output:
==10769== Memcheck, a memory error detector
==10769== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==10769== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
==10769== Command: ./tachyon -s /HOME_ann/BII/biidurgak/test_new_tachyon/Tachyon_v5_improvedQueryTime/settings_smallNR
==10769==
==10769== Thread 5:
==10769== Invalid read of size 4
==10769== at 0x342669C9DE: std::string::assign(std::string const&) (in /usr/lib64/libstdc++.so.6.0.8)
==10769== by 0x42E01A: std::pair::operator=(std::pair const&) (stl_pair.h:152)
==10769== by 0x42B27A: boost::lockfree::detail::ringbuffer_base >::pop(std::pair&, std::pair*, unsigned
long) (spsc_queue.hpp:154)
==10769== by 0x428719: boost::lockfree::detail::compile_time_sized_ringbuffer, 2ul>::pop(std::pair&) (spsc_queue.hpp:305)
==10769== by 0x425DEA: boost::lockfree::spsc_queue, boost::lockfree::capacity, boost::parameter::void_>::pop(std::pair&) (spsc_queue.hpp:572)
==10769== by 0x41BE16: findInDatabase() (Tachyon.cpp:103)
==10769== by 0x4351D4: boost::detail::thread_data::run() (thread.hpp:117)
==10769== by 0x4E53D01: thread_proxy (in /HOME_ann/BII/biidurgak/test_new_tachyon/boost_install/boost_1_55_0/lib/libboost_thread.so.1.55.0)
==10769== by 0x342120673C: start_thread (in /lib64/libpthread-2.5.so)
==10769== by 0x34206D3D1C: clone (in /lib64/libc-2.5.so)
==10769== Address 0xfffffffffffffff8 is not stack'd, malloc'd or (recently) free'd
==10769==
==10769==
==10769== Process terminating with default action of signal 11 (SIGSEGV)
==10769== Access not within mapped region at address 0xFFFFFFFFFFFFFFF8
==10769== at 0x342669C9DE: std::string::assign(std::string const&) (in /usr/lib64/libstdc++.so.6.0.8)
==10769== by 0x42E01A: std::pair::operator=(std::pair const&) (stl_pair.h:152)
==10769== by 0x42B27A: boost::lockfree::detail::ringbuffer_base >::pop(std::pair&, std::pair*, unsigned long) (spsc_queue.hpp:154)
==10769== by 0x428719: boost::lockfree::detail::compile_time_sized_ringbuffer, 2ul>::pop(std::pair&) (spsc_queue.hpp:305)
==10769== by 0x425DEA: boost::lockfree::spsc_queue, boost::lockfree::capacity, boost::parameter::void_>::pop(std::pair&) (spsc_queue.hpp:572)
==10769== by 0x41BE16: findInDatabase() (Tachyon.cpp:103)
==10769== by 0x4351D4: boost::detail::thread_data::run() (thread.hpp:117)
==10769== by 0x4E53D01: thread_proxy (in /HOME_ann/BII/biidurgak/test_new_tachyon/boost_install/boost_1_55_0/lib/libboost_thread.so.1.55.0)
==10769== by 0x342120673C: start_thread (in /lib64/libpthread-2.5.so)
==10769== by 0x34206D3D1C: clone (in /lib64/libc-2.5.so)
==10769== If you believe this happened as a result of a stack
==10769== overflow in your program's main thread (unlikely but
==10769== possible), you can try to increase the size of the
==10769== main thread stack using the --main-stacksize= flag.
==10769== The main thread stack size used in this run was 10485760.
==10769==
==10769== HEAP SUMMARY:
==10769== in use at exit: 219,895,341 bytes in 4,598,508 blocks
==10769== total heap usage: 36,680,650 allocs, 32,082,142 frees, 1,474,244,383 bytes allocated
==10769==
==10769== LEAK SUMMARY:
==10769== definitely lost: 1,904 bytes in 2 blocks
==10769== indirectly lost: 0 bytes in 0 blocks
==10769== possibly lost: 184,232,229 bytes in 4,598,462 blocks
==10769== still reachable: 35,661,208 bytes in 44 blocks
==10769== suppressed: 0 bytes in 0 blocks
==10769== Rerun with --leak-check=full to see details of leaked memory
==10769==
==10769== For counts of detected and suppressed errors, rerun with: -v
Producer:
void producer(string file) {
ifstream query(file.c_str());
string description = "";
string sequence = "";
string line;
while (getline(query, line)) {
//read description
if (line == "") continue;
if (line.at(0) == '>') {
if (sequence != "") {
pair<string, string> a = make_pair(description, sequence);
while (!queue.push(a))
;
sequence = "";
}
description = line.substr(1);
} else {
sequence += line;
}
}
if (sequence != "" && description != "") {
pair<string, string> a = make_pair(description, sequence);
while (!queue.push(a))
;
}
}
In the consumer I have this:
void Consumer(void) {
pair<string, string>element;
//part of code
while(queue.pop(element)){ //Line 103 in Tachyon.cpp
string queryDescription = element.first;
string sequence = element.second;
//Part of code
}
}
Queue is the global variable:
boost::lockfree::spsc_queue<pair<string, string>, boost::lockfree::capacity<2> > queue;
Global variables, multiple threads (I assume), one reading and another thread writing - you need a synchronization object like mutex or critical section.
Pseudocode:
// Consumer
loop-begin;
Lock();
get-item-into-local-variable
Unlock();
process-local-variable-item;
loop-end
// Producer
void AddItem(item)
{
Lock();
Add-item-into-queue
Unlock();
}

GMP mpf functions causing a segmentation fault

I can not figure out that is causing this error. I just installed GMP on ubuntu. This is a 64 bit OS on an AMD cpu (not sure if it matters). I keep getting a segmentation fault.
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include <time.h>
int main(int argc, char** argv)
{
mpz_t sum, fac;
mpf_t fsum, ffac;
int i;
time_t t;
mpz_init_set_ui(sum, 1);
mpz_init_set_ui(fac, 1);
t = time(NULL);
for(i = 10000; i >= 1; --i)
{
mpz_mul_ui(fac, fac, i);
mpz_add(sum, sum, fac);
if(i % 10000 == 0)
{
printf("%d\n", i);
}
}
printf("Time %d\n", (time(0) - t));
mpf_init(fsum);
mpf_init(ffac);
mpf_set_z(fsum, sum);
mpf_set_z(ffac, fac);
mpz_clear(sum);
mpz_clear(fac);
mpf_div(fac, sum, fac);
mpf_out_str(stdout, 10, 50, fac);
mpf_clear(fsum);
mpf_clear(ffac);
return(EXIT_SUCCESS);
}
This code outputs the following...
10000
Time 0
Segmentation fault (core dumped)
I then tried to run this program with valgrind and this is the output.
==25427== Memcheck, a memory error detector
==25427== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==25427== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==25427== Command: /home/chase/NetBeansProjects/GmpECalc/dist/Debug/GNU-Linux-x86/gmpecalc
==25427==
10000
Time 1
==25427== Invalid read of size 8
==25427== at 0x4E8E590: __gmpn_copyi (in /usr/lib/x86_64-linux-gnu/libgmp.so.10.1.3)
==25427== by 0x400B27: main (main.c:40)
==25427== Address 0x73b0000073c is not stack'd, malloc'd or (recently) free'd
==25427==
==25427==
==25427== Process terminating with default action of signal 11 (SIGSEGV)
==25427== Access not within mapped region at address 0x73B0000073C
==25427== at 0x4E8E590: __gmpn_copyi (in /usr/lib/x86_64-linux-gnu/libgmp.so.10.1.3)
==25427== by 0x400B27: main (main.c:40)
==25427== If you believe this happened as a result of a stack
==25427== overflow in your program's main thread (unlikely but
==25427== possible), you can try to increase the size of the
==25427== main thread stack using the --main-stacksize= flag.
==25427== The main thread stack size used in this run was 8388608.
==25427==
==25427== HEAP SUMMARY:
==25427== in use at exit: 48 bytes in 2 blocks
==25427== total heap usage: 3,706 allocs, 3,704 frees, 27,454,096 bytes allocated
==25427==
==25427== LEAK SUMMARY:
==25427== definitely lost: 0 bytes in 0 blocks
==25427== indirectly lost: 0 bytes in 0 blocks
==25427== possibly lost: 0 bytes in 0 blocks
==25427== still reachable: 48 bytes in 2 blocks
==25427== suppressed: 0 bytes in 0 blocks
==25427== Rerun with --leak-check=full to see details of leaked memory
==25427==
==25427== For counts of detected and suppressed errors, rerun with: -v
==25427== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
The error seems to be occurring at the mpf_div function. However, if I remove this function the error will occur at mpf_out_str. I also tried initializing ffac and fsum to doubles (instead of setting them to the fac and sum) and I get the same error.
Problem is in this lines:
mpz_clear(sum); // You clear the variables, GMP deallocates their memory
mpz_clear(fac);
mpf_div(fac, sum, fac); // You use cleared variables, segfault
Maybe you meant:
mpf_div(ffac, fsum, ffac);

~vector() causes SIGSEGV when exit

Thats the Store Credit problem on Google code jam.
https://code.google.com/codejam/contest/351101/dashboard#s=p0
My code gives out a SIGSEGV after running the large test. But the answer is correct!
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int ps[1000]={0};
vector<int> indice[1000];
int main() {
int cases; scanf("%d", &cases);
for(int j=1;j<=cases;j++) {
printf("Case #%d: ", j);
int c, is; scanf("%d%d", &c, &is);
for(int i=0;i<=c;i++) ps[i]=0;
for(int i=0;i<=c;i++) indice[i].clear();
for (int i = 0; i < is; i++) {
int it; scanf("%d", &it);
indice[it].push_back(i+1);
ps[it]=1;
if (c-it>0&&ps[c-it]) {
int a, b;
a = indice[it][0];
b = indice[c-it][0];
if(c==2*it&&indice[it].size()>1) {
b=indice[it][1];
}
if (a!=b) {
printf("%d %d\n", min(a,b),max(a,b));
}
}
}
}
return 0;
}
So I use valgrind to find out what's going on .. but it seems that it's not my problem.
==17599== Invalid free() / delete / delete[] / realloc()
==17599== at 0x4C2A4BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17599== by 0x401669: __gnu_cxx::new_allocator<int>::deallocate(int*, unsigned long) (new_allocator.h:98)
==17599== by 0x4013CD: std::_Vector_base<int, std::allocator<int> >::_M_deallocate(int*, unsigned long) (stl_vector.h:156)
==17599== by 0x400F60: std::_Vector_base<int, std::allocator<int> >::~_Vector_base() (stl_vector.h:142)
==17599== by 0x400D8D: std::vector<int, std::allocator<int> >::~vector() (stl_vector.h:351)
==17599== by 0x400C48: __tcf_0 (a.cpp:6)
==17599== by 0x5383900: __run_exit_handlers (exit.c:78)
==17599== by 0x5383984: exit (exit.c:100)
==17599== by 0x5369773: (below main) (libc-start.c:258)
==17599== Address 0x1 is not stack'd, malloc'd or (recently) free'd
==17599==
==17599==
==17599== HEAP SUMMARY:
==17599== in use at exit: 128 bytes in 1 blocks
==17599== total heap usage: 4,527 allocs, 4,527 frees, 113,664 bytes allocated
==17599==
==17599== LEAK SUMMARY:
==17599== definitely lost: 0 bytes in 0 blocks
==17599== indirectly lost: 0 bytes in 0 blocks
==17599== possibly lost: 0 bytes in 0 blocks
==17599== still reachable: 128 bytes in 1 blocks
==17599== suppressed: 0 bytes in 0 blocks
==17599== Rerun with --leak-check=full to see details of leaked memory
==17599==
==17599== For counts of detected and suppressed errors, rerun with: -v
==17599== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)
I'm so confused... Could anybody tell me what's going on? I'm a newbie of C++ ..
Thank you very much.
As I understand valgrind, it can't detect that you are writing outside of the bounds of arrays that are staticly allocated. So let's allocate them on the heap.
vector<int> *indice = new vector<int>[1000];
int *ps = new int[1000];
Then, you will see errors come out of valgrind. Including:
==7168== Invalid read of size 8
==7168== at 0x4008D6: main (stl_vector.h:735)
==7168== Address 0x4c39e10 is 8 bytes after a block of size 24,008 alloc'd
==7168== at 0x4A07152: operator new[](unsigned long) (vg_replace_malloc.c:363)
==7168== by 0x400791: global constructors keyed to indice (foo.cc:6)
==7168== by 0x400C35: ??? (in /tmp/foo)
==7168== by 0x4005F2: ??? (in /tmp/foo)
==7168==
==7168== Invalid read of size 8
==7168== at 0x4008DA: main (stl_vector.h:735)
==7168== Address 0x4c39e18 is 16 bytes after a block of size 24,008 alloc'd
==7168== at 0x4A07152: operator new[](unsigned long) (vg_replace_malloc.c:363)
==7168== by 0x400791: global constructors keyed to indice (foo.cc:6)
==7168== by 0x400C35: ??? (in /tmp/foo)
==7168== by 0x4005F2: ??? (in /tmp/foo)
==7168==
And using gdb, I can see that the SIGSEGV occurs when you access indice[1433], which is outside of the bounds of indice.
I also imagine that your actual issue is that for the large dataset, the variables bounds are listed as:
N = 50
3 ≤ I ≤ 2000
Are you sure you shouldn't be allocating 2001 elements, instead of 1000?