Last active
June 4, 2019 18:17
-
-
Save jdee/3db587aa39ffda989945633f87812a26 to your computer and use it in GitHub Desktop.
buffer allocation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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