[try Beta version]
Not logged in

 
Segfault on getline

Apr 17, 2013 at 10:08pm
I get wierd segfaults on the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    ......  
    scanf("%d",&n);
    
    for(int i=0;i<n;i++) {
        int x=0,y=0; int tot=0;
        getline(cin,a);
        i=0;
        for(int j=0;j<30;j++) {
            if (a[j]==',' || a[j]==' ' || a[j]=='	') {  //right here
                if (aa[i]!=0) {
                    i++;
                }
            } else {
                aa[i]++;
            }
        }
    .......


My guess is there is some crass mishandling of input here, but I really don't see where.
Apr 17, 2013 at 10:26pm
What are definitions of a and aa? Why did you decide that a has 30 characters?
Apr 17, 2013 at 10:31pm
Sorry, I didn't include the declarations.

1
2
3
string a;
string b;
vector <int> aa,bb;


It's for an algorithm problem. I store the input in a and b then parse after and store the results on aa and bb The problem is only with the getline, if I'm not mistaken.
Last edited on Apr 17, 2013 at 10:32pm
Apr 17, 2013 at 11:25pm
bump.
Apr 17, 2013 at 11:33pm
> Why did you decide that a has 30 characters?


Also, ¿where do you set the size of `aa'?

Use better identifiers
Apr 18, 2013 at 2:10am
a will be empty after the scanf if the number extracted is followed by a newline.

1
2
'	'
doesn't represent what you think it represents. (had to add the newline to preserve the spaces.)

You are reusing the i from the outer loop in the loop body. Bad practice.

Actually describing what your code is intended to do would be helpful, as would providing a compilable example that exhibits the problem.
Last edited on Apr 18, 2013 at 2:13am
Apr 18, 2013 at 5:07am
Also scanf returns a value - you should always assign & test it to see how successful it was before using any variable read in by it.

Why are you using scanf in a C++ program - learn how to use cin or stringstreams.
Apr 18, 2013 at 9:29am
Ok, here is a compilable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	int n;
	string a = "";
	string b = "";
	vector < int >aa, bb;
	int i;


	cin >> n;

		int x = 0, y = 0;
		int tot = 0;
		cin.ignore();
		// cout << endl;
		cout << '1';
		getline(cin, a);
		cout << '2';
		cout << a;
                cout << '3';


It segfaults before printing '2', and I'm a bit clueless.
Apr 18, 2013 at 10:09am
on line 7 you set i=0;, which means your have an infinite loop
Apr 18, 2013 at 4:02pm
I've fixed that, however it has nothing to do with the segfault. It seems to happen in the getline statement, because when running the above code it prints '1', but not '2'.
Topic archived. No new replies allowed.