Assertion Error

I keep getting an assertion failure with the following code.

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
FieldBuilder field ("alexandria_city.dat", 40); //creating the object

//Constructor
FieldBuilder::FieldBuilder(const char* filepath, int numOfRecs){
	recs = new float[numOfRecs*4];
	string line;
	int length = 0;

	ifstream data(filepath);
	if(data.is_open())
	{
		for(int i = 0;data.good(); i++)
		{
			getline(data, line);
			for(int j = 1; j < line.length(); j++)
			{
				length++;
				if(line.substr(j,1) == " " || line.substr(j,1) == ";")
				{
					recs[i] = stof(line.substr(j-length, length));
					length = 0;
					i++;

				}
			}
			length = 0;
		}
	}
}

//List of data
262 607 117 298;
175 464 294 143;
175 607 80 20;
385 607 84 20;
175 212 110 252;
356 212 113 252;
285 212 71 169;
308 175 26 37;
17 308 133 280;
495 273 135 355;
630 496 8 132;
630 273 8 120;
150 304 25 56;
150 384 25 136;
150 544 25 47;
469 304 26 56;
469 384 26 136;
469 544 26 47;
630 416 272 54;
902 409 44 88;
946 49 88 806;
1034 769 562 86;
1271 855 88 51;
1596 49 88 806;
1034 49 562 86;
1684 409 51 88;
1271 0 88 49;
1035 409 51 88;
1271 717 88 51;
1544 409 51 88;
1271 138 88 51;
1086 189 88 528;
1174 189 282 51;
1456 189 88 528;
1174 667 50 28;
1174 409 51 88;
1271 240 88 99;
1226 339 178 229;
1271 588 88 99;
1175 409 88 281;


The purpose of the code is to sort through a data list that has 4 numbers per line separated by spaces and each line ends with a semicolon. I have exactly 40 lines and 4 numbers per line. I also checked the value of i after all of the data had been imported and it was 159. The other thing I tried was break points to see where it was crashing and the error doesn't appear until the last curly bracket of the constructor.

What did solve the problem was instead of multiplying numOfRecs by 4 I changed it to 5 and the error went away, but I don't want to be allocating memory that I won't be using.

Error Message:
Debug Assertion Failed!

Expression:_CrtIsValidHeapPointer(pUserData)
This message means there's a segmentation fault.

Your code seems a bit complicated, why not use stringstreams ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    recs = new float[numOfRecs*4];
    string line;

    ifstream data(filepath);
    if(data.is_open())
    {
        int i = 0;
        while( getline(data,line )
        {
           std::stringstream sstr( line );
           while( sstr >> recs[i] )
           {
               i++;
           }
        }
    }
That solved the issue.
I'm just starting to learn C++ so I don't really know how to use string streams.
Could you elaborate as to how the code you posted works?
Topic archived. No new replies allowed.