Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring hardcoded std::string causes buffer overflow

I have the following line in my program that causes a run-time warning:

if (!is_directory("C:\\NGFMS_Debug\\Files") && !create_directories("C:\\NGFMS_Debug\\Files"))

The text of the warning is as so: "A buffer overrun has occurred in XXX.exe which has corrupted the program's internal state."

The warning comes in the call to "is_directory(...)". I'm guessing the space for the string isn't getting allocated, but I thought syntax like this was legal.

The is_directory function is a part of boost/filesystem.hpp and I am using the following namespaces:

using namespace boost;
using namespace boost::filesystem;
using namespace std;

This is getting compiled under VS2005 C++. Any ideas?

Update

I tried a couple different things and stepped through the code and here is what I found.

If I do this

char* path_chars_c;
path_chars_c = "C:\\Debug\\Files";
string path_str_c(path_chars_c);

The variable path_chars_c contains the appropriate string, but the variable path_str_c contains garbage after initialization. So it appears that the string initialization is broken here. Has anyone ever seen this?

like image 248
Ian Avatar asked Feb 13 '12 21:02

Ian


People also ask

Can a string overflow C++?

The std::string generally protects against buffer overflow, but there are still situations in which programming errors can lead to buffer overflows.

Which C function can cause buffer overflow and why?

That is why the safest basic method in C is to avoid the following five unsafe functions that can lead to a buffer overflow vulnerability: printf , sprintf , strcat , strcpy , and gets . Unfortunately, the base C language provides only one safe alternative: fgets (to be used instead of gets ).

What is buffer overflow in C++?

A buffer overflow is a type of runtime error that allows a program to write past the end of a buffer or array — hence the name overflow — and corrupt adjacent memory. Like most bugs, a buffer overflow doesn't manifest at every program execution.


1 Answers

This is a surprising error -- that seems like a pretty standard use of boost::filesystem::is_directory(). Have you tried stepping into it w/ a debugger to see where the issue happens?

One (remote) possibility comes to mind -- if you are linking libraries that have NDEBUG enabled with libraries that have NDEBUG disabled, you can run into trouble. In particular, a few boost datatypes will allocate some extra debugging fields when debugging is turned on. So if an object gets created by one piece of code that thinks debugging is off, but then used by another piece of code that thinks debugging is on, then you can get random memory errors (such as buffer overflows).

like image 79
Edward Loper Avatar answered Nov 15 '22 11:11

Edward Loper