在Windows下对Visual C编码时,我发现自己被迫修改我的代码,因为功能已弃用,添加了第二个参数,当然还有使用安全功能(例如以_s结尾)。
我想知道,这些函数是否存在于C标准库中,如果我将它们传输到我的linux分区,我能用C编译器编译它们吗?
当我写一个关于偏移函数的字符串翻转时,我的担忧出现了:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *flipstr(char *str, size_t size, size_t offset);
int main(int , char **)
{
char str[] = "JonSon";
char *p = flipstr(str, sizeof(str), 3);
if (p) {
printf("%s\n", p);
}
return 0;
}
char *flipstr(char *str, size_t size, size_t offset)
{
if (offset > strlen(str)) {
return NULL;
}
char *tmp = (char *)calloc(size, sizeof(char));
strncpy_s(tmp, size, str, offset);
memmove(str, str + offset, strlen(str + offset));
memcpy(str + strlen(str + offset), tmp, strlen(tmp));
free(tmp);
return str;
}
答案 0 :(得分:5)
不,大多数都不是标准的,你不应该只是因为微软的某个人决定“弃用”标准库的一半而不是非标准的扩展。当然,他们所做的事情有一些理由,但最终它简直荒谬。您最好禁用警告并编写可移植的C / C ++。
答案 1 :(得分:0)
这里有几个问题......
首先,there is nothing wrong with using strcpy
,这是一个神话。它并没有被弃用,那只是微软gaga。
第二,strncpy
was never intended to be a safe version of strcpy
。除了古老的Unix中的旧的非标准字符串格式之外,它从来没有打算用于任何东西。
第三,strncpy
不安全且危险。请参阅this和this。有很多博客可以找到。
所以忘了strncpy
,因此也忘了strncpy_s
。在C11边界检查接口中实际上有一个名为strncpy_s
的函数(对于编译器来说,这不是强制实现的)。
如果这个C11标准功能与同名的非标准Microsoft垃圾功能完全兼容,我不知道。我不会指望它。但是,由于Visual Studio 2015是一个90年代早期的古老编译器,所以无论如何都不能使用C11。