I am learning some new things in C++, and I was trying to test this strncpy_s function from Visual C++. However I am running into some problems as program crashes and I dunno whats going on but I am sure it is a pretty stupid problem. The source code is something like this:
#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <cstring>
int main()
{
char *p;
p=(char *)malloc(sizeof(char)*strlen("Hello!\n"));
strncpy_s(p,strlen("Hello!\n"),"Hello!\n",strlen("Hello!\n"));
std::cout << p;
std::cout << strlen("Hello!\n") << std::endl;
return 0;
}
As I said I am not using std::string coz I want to try this new function and know how it works.
I take my comments back, I read the documentation more carefully. Your code is passing invalid parameters, and is invoking the invalid parameter handler. Maybe that’s what’s happening. Namely:
This line allocates room for 7 characters, which is the length of the string, but not enough room for a null terminator. (This is generally an error)
The documentation for
strncpy_ssays: These functions try to copy the first D characters of strSource to strDest, where D is the lesser of count and the length of strSource. If those D characters will fit within strDest (whose size is given as numberOfElements) and still leave room for a null terminator, then those characters are copied and a terminating null is appended; otherwise, strDest[0] is set to the null character and the invalid parameter handler is invoked, as described in Parameter Validation.Are you possibly seeing the “invalid parameter handler”?