I'm new to C++ and Microsoft Visual Studio and I'm currently working on a lab for my data structures class, I've finished my code, but when I build and run my program it throws this error:
std::bad_alloc at memory location 0x0018C9C0.
I googled this error and I found that this error is thrown if there isn't enough memory allocated for the program or the program is trying to allocate an infinite amount of memory for something. I tried to allocate more memory in the program properties but that didn't seem to help. Looking over my code, i can't find anything that would throw this error. Here is my code for reference:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
string line;
string value;
string linesArray[200];
int i = 0;
int j = 0;
int finalLine = 158;
getline(cin, line, '\n');
getline(cin, line, '\n');
/* First Line */
for (i; i < finalLine; ++i) {
getline(cin, line, '\n');
for (j; j <= 24; ++j) {
if (j = 0) {
line = line.replace(line.find(','), line.find_first_of(','), string(30 - line.find(','), ' '));
}
line = line.replace(line.find(','), line.find_first_of(','), string(20 - line.find(','), ' '));
}
linesArray[i] = value;
cout << linesArray[i] << endl;
}
return 0;
}
I tried creating a pointer to find the address that it shows in the error, but I couldn't locate it. Any help is greatly appreciated.
EDIT: Sorry that i didn't make myself clear, my input is a txt file in the format of a csv. I take in the information and on the first column of each line I place 30 spaces minus the length of the value and on the rest of the values I place 20 spaces minus the length of the value, unless there is no value, in which I place a zero with 19 spaces.
Example input:
Albania,14,29365,43301,,,,,,,13,27867,41066,,,,,,,1,1498,2235,,,
Change this:
if (j = 0) {
to this:
if (j == 0) {
for a start. And try again...
I don't suspect that your code allocates that much memory to throw std::bad_alloc
exception.
When you do j = 0
every time at the star of your for-loop*, you create an infinite loop...
Notice that after correcting that, I get two warnings of expression result unused
, when compiling with -Wall
flag, which are not the cause of the problem but it would be nice to understand that:
for (j; j <= 24; ++j) {
doesn't need to have j
there and produce the warning, write it like this:
for (; j <= 24; ++j) {
since you don't want to initialize j
there.