Skip to content

Instantly share code, notes, and snippets.

@jdee
Last active June 4, 2019 18:17
Show Gist options
  • Save jdee/3db587aa39ffda989945633f87812a26 to your computer and use it in GitHub Desktop.
Save jdee/3db587aa39ffda989945633f87812a26 to your computer and use it in GitHub Desktop.
buffer allocation
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
#undef BAD
void funcWithNullTerminatedArray(const char* buffer)
{
cout << buffer << endl;
}
void funcWithData(const void* data, size_t size)
{
const char *input = static_cast<const char *>(data);
// Need to make a dynamically sized copy for some reason.
#ifdef BAD
char *buffer = new char[size];
memcpy(&buffer[0], input, size);
#else
// Don't use new/delete.
vector<char> buffer(input, input + size * sizeof(char));
#endif // BAD
// could throw
funcWithNullTerminatedArray(&buffer[0]);
#ifdef BAD
delete[] buffer;
#endif // BAD
}
int
main(int argc, char **argv)
{
const char* input = "Ahoy!";
funcWithData(input, strlen(input) + 1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment