Segment fault for C++ program when return vector


 
Thread Tools Search this Thread
Top Forums Programming Segment fault for C++ program when return vector
# 1  
Old 10-28-2014
Segment fault for C++ program when return vector

I am trying to reverse complement DNA sequence (string) with a short c++ code using boost library. Code was compiled without any warning/error, but ran into Segmentation fault.
My guess is the function to return a vector, but not sure.
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/assign.hpp>

using namespace std;
using namespace boost::assign;

vector <char> revcomp(string str) 
{
vector <char> str_rc;
map <char, char> m = map_list_of('A','T')('T','A')('G','C')('C','G');

for (unsigned i = str.size(); i >= 0 ; --i)
{
str_rc.push_back(m[str[i]]);        //get all the chars except str[0]
}
str_rc.push_back(m[str[0]]);        //get the first char 

return str_rc;
}

int main()
{
vector <char> str2;
string str1 = "ATCGTTTCCC";
str2 = revcomp(str1);

vector<char>::iterator itr2;
for (itr2 = str2.begin(); itr2 != str2.end(); ++itr2)
{
cout << *itr2;
}
cout << endl;

return 0;
}

Code:
$ g++ -Wall revcomp.cpp 
$ ./a.out
Segmentation fault

Can anyone look into it? Thanks a lot!
# 2  
Old 10-28-2014
This is the error:

Code:
for (unsigned i = str.size()-1; i >= 0 ; --i)

An unsigned number is never going to be less than zero, making this an infinite loop. Some compilers will warn you about this.

That said, this code looks suspect in a number of ways. Why are you using strings as the input and vector as the output -- why not vector or string for both? Why return giant vectors since it means it'll be copying them again and again and again and again and again? Pass one in as a reference.

Above all, why use boost? You will be chained to that depleted uranium lawn gnome forever. There's plenty of ways to initialize a map.

Code:
const char *i[]={"AG", "TC"};
for(int n=0; i[0][n]; n++)  { m[i[0][n]]=m[i[1][n]]; m[i[1][n]]=m[i[0][n]]; }

Or don't even use a map at all:

Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static const unsigned char map[256]={
        ['A']='T',      ['T']='A',      ['G']='C',      ['C']='G'       };

int main(int argc, char *argv[])
{
        int n;
        const char *input="ATCGTTTCCC";
        char *output=strdup(input);

        for(n=0; input[n]; n++) output[n]=map[input[n]];

        printf("%s = %s\n", input, output);
}

Vectors and maps have made this problem more difficult, not less.

Last edited by Corona688; 10-28-2014 at 02:49 PM..
This User Gave Thanks to Corona688 For This Post:
# 3  
Old 10-28-2014
Quote:
Originally Posted by Corona688
...

Above all, why use boost? You will be chained to that depleted uranium lawn gnome forever. There's plenty of ways to initialize a map.

...
LOL
# 4  
Old 10-28-2014
Above all, why use boost?
1) It's simply a learning trial by "copy-paste" and still at stage of "try and error" to understand more, hopefully;
2) The purpose is to make a function which will be combined to other .cpp code. Modified from a snippet online as was told "ultra-fast"!
Code:
// http://www.bashthat.com/2014/09/30/reverse-complement-response.html
#include <boost/assign.hpp>

using namespace std;
using namespace boost::assign;

//compile with g++                                                          

int main( int argc,const char *argv[] )
{
  string str = argv[1];
  map<char, char> m = map_list_of ('A', 'T') ('T', 'A') ('G', 'C') ('C', 'G');

  string::iterator it;
  for ( it = str.begin() ; it != str.end(); ++it )
  {
    cout <<  m[*it] ;
  }
  cout << endl;
}

Am I stubborn and offending if I insist C++, as I need modify your code to reverse the output and then integrate it into other .cpp code?
Thanks a lot in any way!

Last edited by yifangt; 10-28-2014 at 03:24 PM..
# 5  
Old 10-28-2014
Quote:
Originally Posted by yifangt
Above all, why use boost?
1) It's simply a learning trial by "copy-paste" and still at stage of "try and error" to understand more, hopefully;
2) The purpose is to make a function which will be combined to other .cpp code. Modified from a snippet online as was told "ultra-fast"!
You are learning from suspicious sources. It is not "fast" to create and initialize a new map every time you call that function. It is especially not fast to return a vector by value.
Quote:
Am I stubborn and offending if I insist C++
Frankly?

My "pure C" code is one cout away from being "pure C++" code. That it looks so mysterious means you've skipped learning big, important chunks of both. It's like trying to avoid using variables of type 'int', or doing everything by calling system("this"); system("that");

Learning how arrays, strings, structures, and pointers actually work will explain almost everything that's baffling you right now. Then you'll be equipped enough to actually troubleshoot your problems and learn more, and take proper advantage of the standard template library -- most of its design imitates them, after all. Maps and vectors imitate arrays, map[index]. Iterators imitate pointers to arrays(and crash all the same ways as them): iterator->content, iterator++... If you don't understand those, you'll never know what you're looking at.

And STL strings imitate real strings (which are themselves, arrays). Notice how little really changes when I substitute one for the other.

Code:
#include <iostream>
#include <string>

using namespace std;

unsigned char m[256];

int main() {
        int n;
        string input="ATCGTTTCCC";
        string output=input;
        m['A']='T';     m['T']='A';     m['G']='C';     m['C']='G';

        for(n=0; n<input.length(); n++) output[n]=m[input[n]];

        cout << input << " " << output << "\n";
        return(0);
}


Last edited by Corona688; 10-28-2014 at 04:22 PM..
This User Gave Thanks to Corona688 For This Post:
# 6  
Old 10-28-2014
Learning how arrays, strings, structures, and pointers actually work will explain almost everything that's baffling you right now.
I am very aware of that, which reminds me of my early posts in this forum. Learning by "practice" related to real problem is better, like this one and the strtok() function......
Am I stubborn and offending if I insist C++
As I have the same feeling like most of the beginners that sometimes C++ is easier to catch than C, and I am not able to mix C with C++ code together in one program at this moment. Neither do I want get lost when trying to solve one problem, so that I asked for C++.
OK, here is a modified version of the code, and I hope it is a improved version from "professional views"
Code:
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;
string revcomp(string);

int main(int argc, char *argv[]) 
{
string str = argv[1];
string str2 = revcomp(str);

cout << str << " = " << str2 << endl;

 return 0;
}

string revcomp(string input)
{
unsigned char m[256];
int n;
string output = input;

m['A'] = 'T'; m['T'] = 'A'; m['C'] = 'G'; m['G'] = 'C';
m['a'] = 'T'; m['t'] = 'A'; m['c'] = 'G'; m['g'] = 'C';

for (n = 0; n < input.length(); n++)
{
output[n] = m[input[n]];
}
string result = output;
reverse(result.begin(), result.end());

return result;
}

Code:
$ g++ -Wall test.cpp 
$ ./a.out aCTGCTACCC
aCTGCTACCC = GGGTAGCAGT

Which is what I need.
Thank you so much again!
# 7  
Old 10-28-2014
Quote:
Originally Posted by yifangt
Learning how arrays, strings, structures, and pointers actually work will explain almost everything that's baffling you right now.
I am very aware of that, which reminds me of my early posts in this forum. Learning by "practice" related to real problem is better, like this one and the strtok() function.
You have learned one way to avoid your blind spots, but your blind spots are still there.
Quote:
Am I stubborn and offending if I insist C++
As I have the same feeling like most of the beginners that sometimes C++ is easier to catch than C
Would you say you could program Perl if you just had line after line of system("echo hello world"), system("mv file1 file2"), system("echo $variable") ?

You understand integers and for-loops, and that's about all. Everything else you've just "shelled out" to an external library. Your programming comfort zone is very, very small.

If you don't recognize something, that doesn't make it "C". You've thrown out big parts of both languages along the way.
Quote:
I am not able to mix C with C++ code together in one program at this moment.
Labeling everything you don't understand as "C" and therefore "out of the curriculum" is part of the problem. You've found one C++ library you like and decided that must be what the language is all about. It's not. You've overlooked something important.

I seriously think you should try and program without STL vector, string, and map for a while.

Last edited by Corona688; 10-28-2014 at 06:26 PM..
This User Gave Thanks to Corona688 For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

Segment fault related to strlen.S

Hello, This function was copied into my code, which was compiled without error/warning, but when executed there is always Segmentation fault at the end after the output (which seems correct!): void get_hashes(unsigned int hash, unsigned char *in) { unsigned char *str = in; int pos =... (7 Replies)
Discussion started by: yifangt
7 Replies

2. Programming

Segment-fault handling for pthreads

Hi I have struggling a week to fix a program , in the begining i got SIGBUS , but after many attempts still the program gets SIGSEGV segment fault , In bellow i post the seg fault log + source codes. would really appreciate if experts help me to fix this segment fault error. any advice is... (2 Replies)
Discussion started by: pooyair
2 Replies

3. Programming

Segmentation fault in other systems C program

Hello everybody, I've been working on a program on my Linux box, after finished the code, i compile it with gcc -Wall option, so i can see what's wrong or unused. The Walll output shows nothing, so there are no loose ends on the program. I run the program on my system, and it works PERFECTLY.... (5 Replies)
Discussion started by: Zykl0n-B
5 Replies

4. Programming

why segment fault,

I always get segment fault, why? can sb help me and modify it, I have spend on much time on #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <string.h> #define MAX 10 pthread_t thread; void *thread1() { int *a; int i, n; ... (1 Reply)
Discussion started by: yanglei_fage
1 Replies

5. Programming

Data segment or Text segment

Hi, Whether the following piece of code is placed in the read-only memory of code (text) segment or data segment? char *a = "Hello"; I am getting two different answers while searching in google :( that's why the confusion is (7 Replies)
Discussion started by: royalibrahim
7 Replies

6. Programming

Memory Fault (core dumped) in ttpy program

I´m writing this program in QNX , I`m kinda new to UNIX and programing in general, and when I try to run it it gives me the Memory Fault error. Can anyone help? #include <stdio.h> #include <fcntl.h> void main(void) {int a,ter; char buf; printf("a="); scanf("%d",a); ter=open... (6 Replies)
Discussion started by: GiganteAsesino
6 Replies

7. Programming

a strange segment fault about ltp-posix test

Hi all In the ltp-posix test,there is a case in open_posix_testsuite\conformance\interfaces\timer_gettime\speculative/6-1.c I run the above code,it will has a segment fault, if I modify it to below,it works well Anybody can tell me why? (1 Reply)
Discussion started by: yanglei_fage
1 Replies

8. Programming

Seg Fault Running AIX COBOL program

Hi some help read............ I'm getting a segmentation fault when I run an AIX COBOL/Db2 program. I initiate the program from the command line, but it hangs, and then when I press enter it generates a segmantation fault and produces a core dump. The box is running AIX software level ... (5 Replies)
Discussion started by: steve_f
5 Replies

9. Programming

Program received signal SIGSEGV, Segmentation fault.

Dear all, I used debugger from C++ and these are the message I got: Program received signal SIGSEGV, Segmentation fault. 0x00323fc0 in free () from /lib/tls/libc.so.6 (gdb) info s #0 0x00323fc0 in free () from /lib/tls/libc.so.6 #1 0x00794fa1 in operator delete () from... (5 Replies)
Discussion started by: napapanbkk
5 Replies

10. Programming

Segment Fault

When run it, segment fault. What is wrong? #include <stdio.h> #include <stdlib.h> const int max =20; //**************************************************** // Input Matrix //**************************************************** void inMatrixAA(int *AA, int row, int col)... (9 Replies)
Discussion started by: zhshqzyc
9 Replies
Login or Register to Ask a Question