Reputation: 115
I am trying to use cout
to print out c strings from a dynamically allocated 2D char array called charArray
. The snippet where I am printing is here:
for(int k=0; k<intSize; k++)
{
std::cout<<"hello"<<std::endl;
std::cout<<charArray[intSize-1-k]<<std::endl;
}
for(int i = 0; i<intSize; i++)
{
delete [] charArray[i];
std::cout<<i<<std::endl;
}
delete [] charArray;
intSize
is how many C strings are in charArray
. However, when I run the program, "hello"
is printed once, and nothing else prints, not the charArray
nor the i in the second for loop. I already confirmed earlier in my code that charArray
is properly filled by successfully using cout
. I ran gdb to try and find the issue, and in gdb the for loops are fully iterating through, so for some reason after the first cout
, the couts stop working. I also tried to flush after every cout
, but still the same thing.
Upvotes: 3
Views: 2719
Reputation: 8475
Try this:
#include <iostream>
int main()
{
const char*nul = nullptr;
std::cout << "before "<< nul << "after\n";
}
The output will be:
before
This is what is happening to you - you are trying to print a nullptr string.
One of charArray[intSize-1-k]
is null. Possibly reading it out of bounds. Writing a null string sets badbit to std::cout
.
To avoid this there are two things you can do:
Validate that a char*
is not null, before printing it.
std::cout.exceptions(std::ostream::failbit);
will make operator<<
throw an exception at the offending line of code. A debugger can catch the exception, and let you find your bug easily (gdb has catch throw
). If you have an exception handler, don't forget to have it call std::cout.clear();
.
Upvotes: 1