What’s the error in this code? I’ve got an error
error C4996: 'strcat': This function or variable may be unsafe. Consider using strcat_s instead
What it’s mean? Another question — the declaration of the struct and the function prototype is legal?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char *join(char *, char *);
printf("%s n", join("duck", "soup"));
}
char *join(char *s1, char *s2)
{
struct {
char buf[256];
} string;
string.buf = "abcd";\ new line. error l-value.
return strcat(strcpy(string.buf, s1), s2);
}
The new line — why there is an error? isn’t string.buf a char pointer? what’s the problem with char *s="abcd"?
Thanks!:)
asked Feb 26, 2015 at 10:20
Dvir NaimDvir Naim
3351 gold badge3 silver badges12 bronze badges
7
The error message is entirely self-explanatory. It’s not clear what it is you don’t understand. For example, in your join function, terrible things would happen if the two strings together are longer than 255 characters.
Also, your join function is totally broken. It returns a pointer to a buffer that no longer exists once it returns since you allocated it on the stack that you are returning from.
answered Feb 26, 2015 at 10:23
David SchwartzDavid Schwartz
177k17 gold badges208 silver badges271 bronze badges
1
That’s your implementation trying to be helpful.
You can stop it from doing that by adding the following #define at the top of your code
#define _CRT_SECURE_NO_WARNINGS
or follow the suggestion and use strcat_s().
answered Feb 26, 2015 at 10:24
pmgpmg
105k12 gold badges125 silver badges198 bronze badges
The first message is because strcat doesn’t check if the target storage is big enough to hold the concatenated string. You might get a buffer overflow. strcat_s has an additional parameter which is the buffer length. It will make sure there is no buffer overflow.
Regarding you second question, the code in join() is bogus.
What you do is declare a local variable that is an array of 256 char. As a local variable it will be «destroyed» when join() terminates.
You then copy s1 into this buffer. Note that the buffer could be too small and you would get a buffer overflow.
Then you call strcat with the local variable buffer as first argument. The result is that s2 will be appended to s1 in the local variable buffer.
The value return by strcat is a pointer on the buffer.
When join() returns, the buffer is «destroyed» and the pointer becomes invalid.
Note that another problem in you code is to declare the function join() inside of main. You must move this line out of the main function.
The way you defined your struct and string variable is correct. It is the way you perform the join() that is bogus.
![]()
Arun A S
5,9774 gold badges29 silver badges41 bronze badges
answered Feb 26, 2015 at 10:33
chmikechmike
20.3k21 gold badges80 silver badges100 bronze badges
2
|
suas_hiatus 2 / 2 / 0 Регистрация: 14.06.2014 Сообщений: 71 |
||||
|
1 |
||||
|
06.09.2015, 19:55. Показов 7033. Ответов 4 Метки нет (Все метки)
Ошибка C4996 ‘strcat’: This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. Подскажите, может их заменить как ( если заменять на strcpy_s то возникает ошибка отсутствия аргументов, так что тоже не знаю что делать) Подскажите, что делать? :#
__________________
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
06.09.2015, 19:55 |
|
Ответы с готовыми решениями: Что лучше применить: sprintf или strcat и strcpy? Писал программу, использовал sprintf(cVar1, "%s",…
Помогите, пожалуйста! Решаю 2 упражнение главы 12 учебника Стивена Прата. Есть… Использование strcpy_s strcpy/strcpy_s Есть класс (упрощенно): class const_string 4 |
|
easybudda Модератор
11647 / 7159 / 1700 Регистрация: 25.07.2009 Сообщений: 13,116 |
||||
|
06.09.2015, 19:59 |
2 |
|||
|
Решение
To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
в самом начале файла. К чему только всё это в С++? Чем std::string не угодил?
1 |
|
2 / 2 / 0 Регистрация: 14.06.2014 Сообщений: 71 |
|
|
06.09.2015, 20:05 [ТС] |
3 |
|
Добавлено через 30 секунд
Чем std::string не угодил? Да без понятия, если честно. Только начинаю изучать, и встретилась эта функция. Я так понимаю, что я делаю через левое колено, и можно было через std::string? А за ответ спасибо, заработало)
0 |
|
Модератор
11647 / 7159 / 1700 Регистрация: 25.07.2009 Сообщений: 13,116 |
|
|
06.09.2015, 20:21 |
4 |
|
Я так понимаю, что я делаю через левое колено, и можно было через std::string? Можно и так сказать. strcpy(), strcat() и иже с ними — наследие языка С, где строки представлялись последовательностью байтов, оканчивающейся нулевым байтом. В С++ есть довольно удобный класс string. Если точно для себя решили освоить именно С++, а не С, рекомендую для работы со строками им и пользоваться. Но, разумеется, представление о строках в С-стиле и функциях для работы с ними лишним не будет.
0 |
|
2758 / 1912 / 569 Регистрация: 05.06.2014 Сообщений: 5,561 |
|
|
06.09.2015, 20:22 |
5 |
|
Да без понятия, если честно. Только начинаю изучать, и встретилась эта функция. Я так понимаю, что я делаю через левое колено, и можно было через std::string? Через левое колено делали вашу Студию, которая отказывается использовать стандартную функцию strcat и хочет НЕ стандартную strcat_s.
0 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
06.09.2015, 20:22 |
|
5 |
When I am using Visual Studio (MSVC), and using the strcat function, I get the error
error C4996: ‘strcat’: This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
If I was to make a project which was for compilers like GCC aswell, is there a way of detecting if these safe functions are needed, for example MSVC macro?
Dirk
10.6k2 gold badges33 silver badges48 bronze badges
asked Feb 18, 2014 at 9:19
7
You can use conditional compilation for cross-platform code. Such as:
#ifdef WIN
strcat_s(...
#else
strcat(...
#endif
MSVC compiler detects such calls of the functions that were acknowledged as deprecated and generates warning C4996 on level 3. So, just compile with this level (or more) and look at warnings.
answered Feb 18, 2014 at 9:32
![]()
Spock77Spock77
3,2062 gold badges28 silver badges39 bronze badges
2
Usually I use #ifdef _CRT_INSECURE_DEPRECATE for this. It’s the macro used by Visual to add these warnings in the first place, so if you’re compiling on a version of Visual that gives warnings, it will be defined.
answered Feb 18, 2014 at 9:22
MedinocMedinoc
6,45118 silver badges38 bronze badges
When I am using Visual Studio (MSVC), and using the strcat function, I get the error
error C4996: ‘strcat’: This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
If I was to make a project which was for compilers like GCC aswell, is there a way of detecting if these safe functions are needed, for example MSVC macro?
Dirk
10.6k2 gold badges33 silver badges48 bronze badges
asked Feb 18, 2014 at 9:19
7
You can use conditional compilation for cross-platform code. Such as:
#ifdef WIN
strcat_s(...
#else
strcat(...
#endif
MSVC compiler detects such calls of the functions that were acknowledged as deprecated and generates warning C4996 on level 3. So, just compile with this level (or more) and look at warnings.
answered Feb 18, 2014 at 9:32
![]()
Spock77Spock77
3,2062 gold badges28 silver badges39 bronze badges
2
Usually I use #ifdef _CRT_INSECURE_DEPRECATE for this. It’s the macro used by Visual to add these warnings in the first place, so if you’re compiling on a version of Visual that gives warnings, it will be defined.
answered Feb 18, 2014 at 9:22
MedinocMedinoc
6,45118 silver badges38 bronze badges
Hello!
I programmed this member function for a «client» class, where I am receiving through command line something like this: host/path1/path2/path3/filename
And in this function I trying to separate the information between the ‘/’ and store it in my class variables host, path and filename (all of them are of type char*)
However this is not working, when compiling I get:
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.
error C4996: 'strcat': This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
I would like to understand why this functions are «unsafe» and any information about this is well received.
Should I do this another way, like trying to do this with strings?
Should I disable deprecation with _CRT_SECURE_NO_WARNINGS?
I am working in visual studio
Here is my function checkCommand:
bool Client::checkCommand(int argc_, char* arguments)
{
if (argc_ == 2)
{
char* tokens[MAXTOKENS] = { };
char* tokenPtr = strtok(arguments, "/");
int i, totalTokens = 0;
while (tokenPtr != NULL && totalTokens < MAXTOKENS)
{
tokens[totalTokens] = tokenPtr;
tokenPtr = strtok(NULL, "/");
}
this->host = tokens[0];
this->filename = tokens[totalTokens];
this->path = tokens[2];
/*here i concatenate my first path to the rest of the paths*/
for (i = 3; i < totalTokens; i++)
{
strcat(this->path, tokens[i]);
strcat(this->path, "/");
}
return true;
}
else
return false;
}
thank you!
Strcpy_s