Skip to content

Commit 296e51f

Browse files
author
Daniel Kroening
committed
fix potential non-zero termination of a string buffer
1 parent 41d7a45 commit 296e51f

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

src/util/tempdir.cpp

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Author: CM Wintersteiger
1515
#endif
1616

1717
#include <cstdlib>
18-
#include <cstring>
18+
#include <vector>
1919

2020
#if defined(__linux__) || \
2121
defined(__FreeBSD_kernel__) || \
@@ -34,26 +34,30 @@ std::string get_temporary_directory(const std::string &name_template)
3434
std::string result;
3535

3636
#ifdef _WIN32
37-
DWORD dwBufSize = MAX_PATH;
38-
char lpPathBuffer[MAX_PATH];
37+
DWORD dwBufSize = MAX_PATH+1;
38+
char lpPathBuffer[MAX_PATH+1];
3939
DWORD dwRetVal = GetTempPathA(dwBufSize, lpPathBuffer);
4040

4141
if(dwRetVal > dwBufSize || (dwRetVal == 0))
4242
throw "GetTempPath failed"; // NOLINT(readability/throw)
4343

44-
char t[MAX_PATH];
44+
// GetTempFileNameA produces <path>\<pre><uuuu>.TMP
45+
// where <pre> = "TLO"
46+
// Thus, we must make the buffer 1+3+4+1+3=12 characters longer.
4547

46-
strncpy(t, name_template.c_str(), MAX_PATH);
48+
std::size_t size=strlen(lpPathBuffer)+1;
49+
std::vector<char> t(lpPathBuffer, lpPathBuffer+size);
50+
t.resize(size+12);
4751

48-
UINT uRetVal=GetTempFileNameA(lpPathBuffer, "TLO", 0, t);
52+
UINT uRetVal=GetTempFileNameA(lpPathBuffer, "TLO", 0, t.data());
4953
if(uRetVal == 0)
5054
throw "GetTempFileName failed"; // NOLINT(readability/throw)
5155

52-
unlink(t);
53-
if(_mkdir(t)!=0)
56+
unlink(t.data());
57+
if(_mkdir(t.data())!=0)
5458
throw "_mkdir failed";
5559

56-
result=std::string(t);
60+
result=std::string(t.data());
5761

5862
#else
5963
std::string prefixed_name_template="/tmp/";
@@ -64,9 +68,9 @@ std::string get_temporary_directory(const std::string &name_template)
6468
prefixed_name_template+='/';
6569
prefixed_name_template+=name_template;
6670

67-
char t[1000];
68-
strncpy(t, prefixed_name_template.c_str(), 1000);
69-
const char *td = mkdtemp(t);
71+
std::vector<char> t(prefixed_name_template.begin(), prefixed_name_template.end());
72+
t.push_back('\0'); // add the zero
73+
const char *td = mkdtemp(t.data());
7074
if(!td)
7175
throw "mkdtemp failed";
7276
result=std::string(td);

0 commit comments

Comments
 (0)