Segmentation faults && vectors

soo... I was nosing around basic encryption, and have tried to make a decrypt project, which takes in an encrypted message (e.g. 10110 etc.) and a key (e.g. 15, 23, 13, 63).

Now, if working should return a decrypted message which is sorted after the key(
the first letter of the decrypt is the 15th one in the msg, the 2nd is the 23rd, etc)((for those not getting it; i want to count the first 15 numbers of msg, return that 15th number, delete it, count 23 steps further, return and delete that, when end is reached, start over, until the whole msg is decrypted))

So, I mucked my way from one segmentation fault to another, well the same one, just each time I'm finished, I get it.

Here's the code I have atm:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
using namespace std;



int main()
{
std::vector <int> msg;
int inmsg[180] = {1, 1, 1, 1, 1, 0, 0, 0, etc. no need to include all 180 numbers.};
int key[5] = {37,   35, 34, 36, 38};
int i, j, k, count, pos, sizz;
sizz=180;
pos=0;
for (i=0; i<180; i++) msg.push_back(inmsg[i]);

for (k=0; k<36;k++){
    i=0;
for (i=0; i<5;i++){
    count=0;
    for (j=key[i];j>0; j--){
    count++;
    pos++;
        if(count==key[i]){
            count=0;
            cout<<msg[pos];
            msg.erase(msg.begin()+pos);
            sizz--;
        }
    if(pos==sizz)pos=0;
    }
}
}
return 0;
}


which result in this

Segmentation fault

Process returned 139 (0x8b) execution time : 0.012 s
Press ENTER to continue.



(I'm running c::b with gcc on an Asus Eee)
Anyone know a good'n clear guide to dodge these blasted errors?
Or what I can to different with the code? Possibly both?

Thanks...
Did you try using a debugger to find out where in the code it is segfaulting?
On what line is the error?

I'm having trouble reading your code, but I have a feeling that what's happening is that you're going out-of-bounds when your vector shrinks to less than 38 (the largest key) elements.

If you use .at(/*index*/) instead of [/*index*/], then you would have a chance to recover if you use try and catch.

I think. Happy coding.

-Albatross
Last edited on
well, worked fine w/o the for k-loop. But with it I have no idea. Tried the db, but since I've just started with c::b , I drew a blank. Will post if something pops up though.
Aye, time to use the debugger.

compile it with the -g option added.

Run it from the command line as follows:

gdb ./nameOfYourExecutable

then type run when gdb starts up.

It will identify the line that causes the segfault, and will halt there and allow you to interrogate the values to see what the problem is.
Topic archived. No new replies allowed.