I'm trying to get rid of some compiler warnings that say strcpy, sprintf, etc are unsafe.
I get why they're unsafe, but I can't think of a good way to fix the code, in a C++ style.
Here's a excerpt of the code:
extList->names[i]=(char *)malloc(length*sizeof(char));
strcpy(extList->names[i],extName); // unsafe
// strncpy(extList->names[i],extName,length); // also unsafe
Here's the message:
C4996: 'strcpy': This function or variable may be
unsafe. Consider using strcpy_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.
I can't think of a safe way to copy the data over in C++ without knowing the length of the stuff to copy.
I know there's strlen(), but that's also unsafe since it assumes (maybe incorrectly) that the data is null-terminated.
Also:
// used to concatenate:
sprintf(extStr,"%s%s",platExtStr,glExtStr);
C4996: 'sprintf': This function or variable may be unsafe. Consider
using sprintf_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.
Using std::string to concatenate is easy enough, but then I need to get the data into extStr somehow (and not using strcpy, lol). The string::c_str() function returns a pointer to un-modifiable data, so I can't just set extStr equal to it. (And I'm not even sure if the c_str() pointer needs delete called on it later? Does it allocate space using "new"?)
Any advice on this stuff?
This is part of a 10,000 line file that's not mine... so I'm not exactly keen on re-writing the thing in the C++ way.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…