Common vulnerabilities guide for C++ programmers

C++ is not C. That's the first advice we can give. Don't use printf, char* and friends, but instead go the C++ way. If you are forced to do things in the C way, please review the C guidelines.

Memory handling

  • Don't use malloc and free. Use new and delete instead. In case of exceptions in your code, memory allocated by new will be de-allocated cleanly.

String handling

  • Don't use char*, but use the std::string class.
  • Don't use fscanf, but use the » operator together with std::outputstream objects.

File handling

  • Don't use fopen(). Use std::ifstream for reading. For writing, it's more complicated. It requires calling the C open together with the C opening flags, and then using the boost library to get a nice stream from the file descriptor itself:
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
 
namespace io = boost::iostreams;
 
class ex {};
 
int main ()
{
	int fd = open("/my/file", O_WRONLY|O_CREAT|O_EXCL, 0600);
	if (fd == -1)
		throw ex();
	io::stream_buffer<io::file_descriptor_sink> fp (fd);
	std::ostream out(&fp);
 
	out << "Hello, world" << std::endl;
	return 0;
}

After that, just compile it with the -lboost_iostreams flag, and that's it!