Skip to content

Instantly share code, notes, and snippets.

@mipdevbe
Created March 6, 2019 11:19
Show Gist options
  • Save mipdevbe/d48f702b983ef033de0e78cf877ac79e to your computer and use it in GitHub Desktop.
Save mipdevbe/d48f702b983ef033de0e78cf877ac79e to your computer and use it in GitHub Desktop.
// ConsoleApplication2.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <cstdio>
#include <cstdlib>
#include <string>
#include <sstream>
void StringInvalidParameterHandler(
const wchar_t* expression,
const wchar_t* function,
const wchar_t* file,
unsigned int line,
uintptr_t pReserved);
void Examples();
template <size_t size>
errno_t strncpy_security(char (&destination)[size],
char const* source,
size_t _Count)
{
return strncpy_s(destination, source, _Count);
}
int main()
{
_invalid_parameter_handler oldHandler, newHandler;
newHandler = StringInvalidParameterHandler;
oldHandler = _set_invalid_parameter_handler(newHandler);
// Disable the message box for assertions.
_CrtSetReportMode(_CRT_ASSERT, 0);
Examples();
}
void Examples()
{
char dest[10];
errno_t err = strncpy_s(dest, _countof(dest), "How do you do?", _TRUNCATE);
printf(" truncation %s occur\n", err == STRUNCATE ? "did" : "did not");
err = strncpy_s(dest, _countof(dest), "Howdy.", _TRUNCATE);
printf(" truncation %s occur\n", err == STRUNCATE ? "did" : "did not");
strncpy_security(dest, "very very very long", 15);
printf(" new contents of dest: '%s'\n", dest);
}
void StringInvalidParameterHandler(
const wchar_t* expression,
const wchar_t* function,
const wchar_t* file,
unsigned int line,
uintptr_t pReserved)
{
printf("[%s:%ld] in %s\n", __func__, __LINE__, __FILE__);
wprintf(L"Invalid parameter handler invoked: %s\n", expression);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment