Usage of strtok_s() Function

当您需要性能优化时,请考虑 C printf和sprintf,它们快速且易于使用。 但是,它们不能扩展或免受漏洞的攻击。 (存在安全版本,但它们会受到轻微的性能损失。 有关详细信息,请参阅printf_s、_printf_s_l、wprintf_s、_wprintf_s_l和sprintf_s、_sprintf_s_l、swprintf_s、_swprintf_s_l。
by MSDN,某些旧函数,包括strtok()似乎有一些安全性的问题,被strtok_s()代替,新函数新加入了一个参数,感觉新函数比以前那个更好用。使用示例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

char c_string[] =
"1 2 3 4 5";
char sepa[] = " ";
char *token = NULL;
char *next_token = NULL;

int main()
{
// Establish string and get the first token:
token = strtok_s(c_string, sepa, &next_token);

// While there are tokens in "string1" or "string2"
while (token != NULL)
{
// Get next token:
if (token != NULL)
{
printf_s(" %s\n", token);
token = strtok_s(NULL, sepa, &next_token);
}
}
printf("remain:\n");
printf("%d", token);
}

When performance optimization is needed, consider C’s printf and sprintf, which are fast and easy to use. However, they are not scalable or protected from vulnerabilities. (Secure versions exist, but they come with a slight performance penalty. For details, refer to printf_s, _printf_s_l, wprintf_s, _wprintf_s_l and sprintf_s, _sprintf_s_l, swprintf_s, _swprintf_s_l.)
According to MSDN, certain legacy functions, including strtok(), appear to have some security issues and are replaced by strtok_s(). The new function adds an additional parameter, making it seem more user-friendly than the previous one. Example usage is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

char c_string[] =
"1 2 3 4 5";
char sepa[] = " ";
char *token = NULL;
char *next_token = NULL;

int main()
{
// Establish string and get the first token:
token = strtok_s(c_string, sepa, &next_token);

// While there are tokens in "string1" or "string2"
while (token != NULL)
{
// Get next token:
if (token != NULL)
{
printf_s(" %s\n", token);
token = strtok_s(NULL, sepa, &next_token);
}
}
printf("remain:\n");
printf("%d", token);
}

Usage of strtok_s() Function
https://tokisaki.top/blog/cpp-strtok-s/
作者
Tokisaki Galaxy
发布于
2020年8月28日
许可协议