strcpy() error in Visual studio 2012 - c++

so I have this code:
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
...
char* b = new char [10];
strcpy(b, "1234567890");
error: microsoft visual studio 11.0\vc\include\string.h(110) : see declaration of 'strcpy'
How do I fix it?

A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings
Right-click your C++ and chose the "Properties" item to get to the properties window.
Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".
In the "Preprocessor definitions" add
_CRT_SECURE_NO_WARNINGS
but it would be a good idea to add
_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
as to inherit predefined definitions
IMHO & for the most part this is a good approach.

There's an explanation and solution for this on MSDN:
The function strcpy is considered unsafe due to the fact that there is
no bounds checking and can lead to buffer overflow.
Consequently, as it suggests in the error description, you can use
strcpy_s instead of strcpy:
strcpy_s( char *strDestination, size_t numberOfElements,
const char *strSource );
and:
To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.
http://social.msdn.microsoft.com/Forums/da-DK/vcgeneral/thread/c7489eef-b391-4faa-bf77-b824e9e8f7d2

The message you are getting is advice from MS that they recommend that you do not use the standard strcpy function. Their motivation in this is that it is easy to misuse in bad ways (and the compiler generally can't detect and warn you about such misuse). In your post, you are doing exactly that. You can get rid of the message by telling the compiler to not give you that advice. The serious error in your code would remain, however.
You are creating a buffer with room for 10 chars. You are then stuffing 11 chars into it. (Remember the terminating '\0'?) You have taken a box with exactly enough room for 10 eggs and tried to jam 11 eggs into it. What does that get you? Not doing this is your responsibility and the compiler will generally not detect such things.
You have tagged this C++ and included string. I do not know your motivation for using strcpy, but if you use std::string instead of C style strings, you will get boxes that expand to accommodate what you stuff in them.

I had to use strcpy_s and it worked.
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
struct student
{
char name[30];
int age;
};
int main()
{
struct student s1;
char myname[30] = "John";
strcpy_s (s1.name, strlen(myname) + 1 ,myname );
s1.age = 21;
cout << " Name: " << s1.name << " age: " << s1.age << endl;
return 0;
}

Add this line top of the header
#pragma warning(disable : 4996)

If you are getting an error saying something about deprecated functions, try doing #define _CRT_SECURE_NO_WARNINGS or #define _CRT_SECURE_NO_DEPRECATE. These should fix it. You can also use Microsoft's "secure" functions, if you want.

For my problem, I removed the #include <glui.h> statement and it ran without a problem.

Related

Function setenv() not found? [duplicate]

Look my code seems to be correct, according to all the documentation I can find online. My IDE is MS Visual Studio Xpress 4 Windows Desktop 2012, and it's compiler is throwing up the error:
Error 1 error C3861: 'setenv': identifier not found e:\users\owner\documents\visual studio 2012\projects\project1\project1\source1.cpp 18 1 Project1.
Help me!!!
#include <windows.h>
#include <sstream>
#include <ostream>
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
using namespace std;
int howManyInClass = 0;
int main(){
long checklength = sizeof(getenv("classSize"))/sizeof(*getenv("classSize"));
if (checklength==0){
cout<<"Please enter the ammount of students in your class";
cin>> howManyInClass;
cin.ignore();
setenv("classSize", howManyInClass, 1);}
};
Microsoft's runtime library doesn't support the standard setenv() function. You could use their replacement _putenv() or, for portable code, I prefer to use a simple wrapper.
Here's my wrapper with the standard interface:
int setenv(const char *name, const char *value, int overwrite)
{
int errcode = 0;
if(!overwrite) {
size_t envsize = 0;
errcode = getenv_s(&envsize, NULL, 0, name);
if(errcode || envsize) return errcode;
}
return _putenv_s(name, value);
}
You can either use _putenv() which takes a string parameter as the string classSize=7;
ostringstream classSize;
classSize << "classSize=" << howManyInClass;
_putenv(classSize.str().c_str());
...or (preferably) the security enhanced _putenv_s() that takes the key and the value as separate (const char*) parameters;
ostringstream classSize;
classSize << howManyInClass;
_putenv_s("classSize", classSize.str().c_str());
Try _putenv instead of setenv.
msdn _putenv
the reason you encountered the linkage error is that, if you take a look at the content of the library of stdlib.h, you will find that, setenv() is not declared there. At the first glance, it is a C standard API, but looks like Windows do not follow all of the standard. Or, you might be able to configure your VS to use CRT instead of Windows runtime, in that case, I think setenv will be identified.

Why does the compiler still warn me about unsafe strtok even after I define _CRT_SECURE_NO_WARNINGS?

I am using Visual Studio Express 2012 for Windows Desktop.
I always get error
Error C4996: 'strtok': This function or variable may be unsafe.
Consider using strtok_s instead.
To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
See online help for details.
When I try to build the following:
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char the_string[81], *p;
cout << "Input a string to parse: ";
cin.getline(the_string, 81);
p = strtok(the_string, ",");
while (p != NULL) {
cout << p << endl;
p = strtok(NULL, ",");
}
system("PAUSE");
return 0;
}
Why am I getting this error even though I define _CRT_SECURE_NO_WARNINGS, and how do I fix it?
Your #define doesn't work because of the content of your precompiled header file (stdafx.h). The boilerplate one looks like this:
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
It is the last two #includes that cause the problem, those .h files themselves already #include string.h. Your #define is therefore too late.
Beyond defining the macro in the compiler settings instead, the simple workaround is to just move the #define into your stdafx.h file. Fix:
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
This may be an old post but I had a similar problem recently.
I went into the project options -> C/C++ -> Preprocessor -> added _CRT_SECURE_NO_WARNINGS to the list of Preprocessor Definitions.
This way you don´t have to put it in every file.
Try following.
#pragma warning (disable : 4996)
Note the error number is C4996.
It looks like you switched on a compiler option that forces the compiler to consider all warnings as errors. Either switch off this option or indeed use macro _CRT_SECURE_NO_WARNINGS

About Use of #include Preprocessor Directive in C++

I stumble on the following compilation error in C++ with g++ compiler:
error on line line 1 with message:
invalid preprocessing directive #a
(with a caret above the character a) which is followed by another,probably consequent, error on line 4 with message:
cout was not declared in this scope.
The editor i am using is Code blocks 10.05 with mingw.I tried removing .h extension from the iostream file include statement;switching among different File encoding options;and replacing the angular bracket with single quotes and double quotes as well.i am stuck on it.Pardon if it is a duplicate(although i went through several already asked questions in relevance).
The following code illustrates the problem:
#‪include ‬<iostream.h>
int main()
{
cout<< "abc"+8;
cout<< "def"+4;
cout<< "ha";
return 0;
}
cout exists within the namespace std
So either
#‪include‬<iostream>
//...
std::cout << "abc" << 8;
//...
or
#‪include‬<iostream>
using namespace std;
//...
or
#‪include‬<iostream>
using std::cout;
//...
I tend to prefer the 1st if I'm only using it once or twice, The second if I'm using a lot of different pieces from a namespace (and only in a cpp file), or the third if I'm only using a piece or 2 from a namespace but using the same couple many times.
Additionally as stated in the comments, don't use the 2nd one in headers. See: "using namespace" in c++ headers
Also, you have an invalid character in your #include. You can see it in a hex editor or Note how stackoverflow doesn't highlight them the same:
#‪include‬<iostream>
#include<iostream>
Fully working code:
#include<iostream>
using std::cout;
int main()
{
cout << "abc" << 8;
cout << "def" << 4;
cout << "ha";
return 0;
}
Produces the following output abc8def4ha after I corrected for trying to add 8 to a char*
You have to use std::cout, which means that the "cout" keyword is part of the standard library.
The "invalid directive" error is caused by some invisible Unicode characters in the #include directive; perhaps you copied this from a website that embedded some formatting characters in the code. They can be seen in the question, if you look at the source in a hex editor. That error should be fixed by deleting and retyping the #include line.
You'll probably have other errors, since the code is fifteen years out of date; most modern compilers don't provide pre-standard libraries. These days, the standard library headers don't have a .h extension:
#include <iostream>
and nearly all the names they declare are scoped inside the std namespace:
std::cout << "ha";
Finally, "abc"+8 doesn't do anything sensible. The string literal is an array of four characters, and +8 tries to give you a pointer to the ninth character, which doesn't exist. The result is undefined behaviour.
If you want to print "abc" followed by "8", then you want:
std::cout << "abc" << 8;
Try using it like this:-
#‪include ‬<iostream>
using std :: cout;
cout is the part of std library
If you've got caret above a, try retyping your #include.
You might accidentally type alternative i which looks similar but has different code.
Suggestions about std:: are only relevant for the second error you're getting.
I also didn't fully understand what you were trying to achieve with "abc"+8.

C++: Setenv(). Undefined identifier in Visual Studio

Look my code seems to be correct, according to all the documentation I can find online. My IDE is MS Visual Studio Xpress 4 Windows Desktop 2012, and it's compiler is throwing up the error:
Error 1 error C3861: 'setenv': identifier not found e:\users\owner\documents\visual studio 2012\projects\project1\project1\source1.cpp 18 1 Project1.
Help me!!!
#include <windows.h>
#include <sstream>
#include <ostream>
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
using namespace std;
int howManyInClass = 0;
int main(){
long checklength = sizeof(getenv("classSize"))/sizeof(*getenv("classSize"));
if (checklength==0){
cout<<"Please enter the ammount of students in your class";
cin>> howManyInClass;
cin.ignore();
setenv("classSize", howManyInClass, 1);}
};
Microsoft's runtime library doesn't support the standard setenv() function. You could use their replacement _putenv() or, for portable code, I prefer to use a simple wrapper.
Here's my wrapper with the standard interface:
int setenv(const char *name, const char *value, int overwrite)
{
int errcode = 0;
if(!overwrite) {
size_t envsize = 0;
errcode = getenv_s(&envsize, NULL, 0, name);
if(errcode || envsize) return errcode;
}
return _putenv_s(name, value);
}
You can either use _putenv() which takes a string parameter as the string classSize=7;
ostringstream classSize;
classSize << "classSize=" << howManyInClass;
_putenv(classSize.str().c_str());
...or (preferably) the security enhanced _putenv_s() that takes the key and the value as separate (const char*) parameters;
ostringstream classSize;
classSize << howManyInClass;
_putenv_s("classSize", classSize.str().c_str());
Try _putenv instead of setenv.
msdn _putenv
the reason you encountered the linkage error is that, if you take a look at the content of the library of stdlib.h, you will find that, setenv() is not declared there. At the first glance, it is a C standard API, but looks like Windows do not follow all of the standard. Or, you might be able to configure your VS to use CRT instead of Windows runtime, in that case, I think setenv will be identified.

srand(time(NULL)) "Function 'srand' could not be resolved."

I have been trying to debug this problem for a while and quite honestly, I just can't see what I'm doing wrong.
Why is there a syntax error?
#include <iostream>;
#include <time.h>;
#include <stdio.h>;
#include <stdlib.h>;
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
The error I'm getting is,
"Function 'srand' could not be resolved."
I'm well aware now that I don't need the semi-colons after 'include' statements
I'm using Eclipse CDT along with MinGW as my compiler
How I resolved the problem:
It had to do with the MinGW compiler I was using. Switching over to Visual Studio solved the problem.
; at the end of the #include directives are the problem in your code. #include directives don't need (wrong to place indeed) semicolons at the end unlike C++ statements.
[Warning] extra tokens at end of #include directive [enabled by default]
It seems any character after > in the directive causes this error/warning.
#include<iostream>a //error
Change to this:
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
int main(){
cout<<"Hello Main";
}
EDIT:
Regarding the linker issue:
One suggestion is C++ expects types to be explicitly casted between types (more than C). So, use a cast to convert time_t which is returned by the time to unsigned int which is the input parameter type of srand. (And of course this might not be the problem with linker error)
Instead of using stdlib.h, try using <cstdlib>, try if it helps. Because it uses namespace.
Apart from that, I have seen this snippet here. Use that pattern if it helps.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); //use current time as seed for random generator
int random_variable = rand();
cout << "Random value on [0 " << RAND_MAX << "]: "
<< random_variable << '\n';
}
there is already question in SO check if that helps Eclipse Method could not be resolved in a simple program C++
Never use time() to initialize srand()..
EDIT:
Now it seems many people got this kind of problem. I found a question How do I fix Eclipse CDT Error “Function 'isdigit' could not be resolved. He is facing the same problem. The asker suggested a work around to this in his question edit.
Quoted from that question:
I now believe this to be a Code Analysis problem. A better solution is
to edit the Code Analysis options to make "Function could not be
resolved" be a warning instead of an error. That way you can see the
warnings in Problems view, but continue to work. If the function is
REALLY missing, the compiler will tell you! I also have a new theory,
that the problem is with the Code Analyzer following symlinks, because
all of the "missing" functions are in symlinked include files. Would
love any input on this theory.
Hope that points to solve the problem.
; should not be there after #include.
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include files shoule not end with ;