Nnamdi Nwajagu
Nnamdi Nwajagu

Reputation: 1

Why is my std::vector.push_back throwing a bad_alloc exception

I have a simple loop that reads in a text file and writes it into a character array. Here is the function

void podBase::parseMailingAddyImacroOutput(string a)
{
	fstream inP(a, fstream::in);
	char *buffer = new char[50000];
	int sz_data = 0;
	int nComma = 0;
	string temp = "";
	string *ptr_temp = &temp;
	char z = ' ';
	bool check[3] = { false,false,false };
	_MailingAddy.resize(vectorEntries);
	_CityStateZip.resize(vectorEntries);

	while (inP.get(buffer[sz_data]))
		sz_data++;

	//inP.close();

	

	//3 Commmas
	//First comma: Owner Name
	//Second Comma: Owner mailing street & Num
	//Third Comma: City, State, Zipcode

	for (int i = 0; i < sz_data; i++)
	{

		z = buffer[i];
		if (!isComma(z))
			temp += z;

		if (isComma(z))
			nComma++;

		if (nComma == 1 && !check[0])
		{
			temp.clear();
			check[0] = true;
		}

		if (nComma == 2 && !check[1])
		{
			_MailingAddy.push_back((temp));
			temp.clear();
			check[1] = true;
		}

		if (nComma == 3 && !check[2])
		{
			_CityStateZip.push_back(temp);
			temp.clear();
			check[0] = false;
			check[1] = false;
			check[2] = false;
			nComma = 0;

		}



	}

	


}

Upon execution, the program crashes at the line:

if (nComma == 2 && !check[1])
    {
        _MailingAddy.push_back((temp));
        temp.clear();
        check[1] = true;
    }

trying to execute "push_back" With the reason of "bad_alloc". Regardless of what I try to push_back into the vector, I get this error - So I don't think its a problem of the std::string temp variable. I have done similar methods in this same program many times and have never come across an issue like this. Any insight would be welcome!

Upvotes: 0

Views: 1651

Answers (2)

Mark B
Mark B

Reputation: 96281

You're leaking 50k memory every time you call parseMailingAddyImacroOutput so presumably you ran out of memory.

Upvotes: 5

Nnamdi Nwajagu
Nnamdi Nwajagu

Reputation: 1

I'm not sure why the error wasn't thrown earlier in the program but the error stemmed from the buffer array being too small. Doubled the size and the error is gone.

Upvotes: -2

Related Questions