Reputation: 652
I'm using Visual C++ 2017 to build an OpenGL/GLFW application. However, I'm getting a crash on the delete[]
statement with the message "HEAP CORRUPTION DETECTED : [...] CRT detected that the application wrote to memory after end of heap buffer." in the following function I wrote :
#include <direct.h>
void setwd(char **argv)
{
char *buf = new char[strlen(argv[0])];
strcpy(buf, argv[0]);
// Handle both possible separators
char *p = strrchr(buf, '/');
if(!p)
p = strrchr(buf, '\\');
if(p)
{
*(p + 1) = '\0';
_chdir(buf);
}
delete[] buf;
}
If I delete my call to setwd
, everything works fine. I made sure in debugging that strlen(argv[0])
is never 0.
Worthy of note is that this works perfectly fine if compiled with MSYS2/gcc.
Upvotes: 1
Views: 72
Reputation: 10675
You need one extra character in the buffer, for the null terminator: new char[strlen(argv[0])+1]
Upvotes: 1