* readFile: don't overflow the stack on large files.

This commit is contained in:
Eelco Dolstra 2006-10-30 11:56:09 +00:00
parent 8d17265ac4
commit 8478cd260f

View file

@ -194,12 +194,26 @@ Strings readDirectory(const Path & path)
} }
template <class T>
struct AutoDeleteArray
{
T * p;
AutoDeleteArray(T * p) : p(p) { }
~AutoDeleteArray()
{
delete [] p;
}
};
string readFile(int fd) string readFile(int fd)
{ {
struct stat st; struct stat st;
if (fstat(fd, &st) == -1) if (fstat(fd, &st) == -1)
throw SysError("statting file"); throw SysError("statting file");
unsigned char buf[st.st_size]; /* !!! stack space */
unsigned char * buf = new unsigned char[st.st_size];
AutoDeleteArray<unsigned char> d(buf);
readFull(fd, buf, st.st_size); readFull(fd, buf, st.st_size);
return string((char *) buf, st.st_size); return string((char *) buf, st.st_size);