Skip to content

Commit 5848fca

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

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

src/util/tempdir.cpp

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@ Author: CM Wintersteiger
1212
#include <windows.h>
1313
#include <io.h>
1414
#include <direct.h>
15+
#else
16+
#include <vector>
1517
#endif
1618

1719
#include <cstdlib>
18-
#include <cstring>
1920

2021
#if defined(__linux__) || \
2122
defined(__FreeBSD_kernel__) || \
@@ -34,26 +35,30 @@ std::string get_temporary_directory(const std::string &name_template)
3435
std::string result;
3536

3637
#ifdef _WIN32
37-
DWORD dwBufSize = MAX_PATH;
38-
char lpPathBuffer[MAX_PATH];
38+
DWORD dwBufSize = MAX_PATH+1;
39+
char lpPathBuffer[MAX_PATH+1];
3940
DWORD dwRetVal = GetTempPathA(dwBufSize, lpPathBuffer);
4041

4142
if(dwRetVal > dwBufSize || (dwRetVal == 0))
4243
throw "GetTempPath failed"; // NOLINT(readability/throw)
4344

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

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

48-
UINT uRetVal=GetTempFileNameA(lpPathBuffer, "TLO", 0, t);
53+
UINT uRetVal=GetTempFileNameA(lpPathBuffer, "TLO", 0, t.data());
4954
if(uRetVal == 0)
5055
throw "GetTempFileName failed"; // NOLINT(readability/throw)
5156

52-
unlink(t);
53-
if(_mkdir(t)!=0)
57+
unlink(t.data());
58+
if(_mkdir(t.data())!=0)
5459
throw "_mkdir failed";
5560

56-
result=std::string(t);
61+
result=std::string(t.data());
5762

5863
#else
5964
std::string prefixed_name_template="/tmp/";
@@ -64,9 +69,9 @@ std::string get_temporary_directory(const std::string &name_template)
6469
prefixed_name_template+='/';
6570
prefixed_name_template+=name_template;
6671

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

0 commit comments

Comments
 (0)