strcpy_s 函数在我的代码中不起作用
The strcpy_s function doesn't work in my code
此函数应该将 char[] 复制到分配的存储空间中。由于某种原因,缓冲区对于此操作总是太小。
str(char* f) {
len = strlen(f);
txt = (char*)malloc(len); //txt is a pointer to a char
strcpy_s(txt, len, f);
}
For some reason the buffer is always too small for this operation.
您忘记为空终止符分配内存。一个空字符串需要 space 作为一个字符(终止符)。长度为 1 的字符串需要 space 两个字符 (1 + 1)。长度为 len
的字符串需要 space 个 len + 1
个字符。
也就是说:
- 在 C 中,请改用
strdup
。
- 在 C++ 中,不要使用
strlen
、malloc
或 strcpy_s
(或 strdup
)。我推荐 std::string
.
确保包含 cstring 库
此函数应该将 char[] 复制到分配的存储空间中。由于某种原因,缓冲区对于此操作总是太小。
str(char* f) {
len = strlen(f);
txt = (char*)malloc(len); //txt is a pointer to a char
strcpy_s(txt, len, f);
}
For some reason the buffer is always too small for this operation.
您忘记为空终止符分配内存。一个空字符串需要 space 作为一个字符(终止符)。长度为 1 的字符串需要 space 两个字符 (1 + 1)。长度为 len
的字符串需要 space 个 len + 1
个字符。
也就是说:
- 在 C 中,请改用
strdup
。 - 在 C++ 中,不要使用
strlen
、malloc
或strcpy_s
(或strdup
)。我推荐std::string
.
确保包含 cstring 库