C strcpy 函数
最后修改:2025 年 4 月 8 日
字符串操作在 C 编程中至关重要,而 strcpy 是在内存位置之间复制字符串的关键函数。本教程将深入介绍 strcpy,包括其语法、用法和潜在陷阱。我们将探讨实际示例,并为关键应用程序讨论更安全的替代方案。理解 strcpy 有助于进行字符串操作,同时保持程序的安全性和可靠性。
什么是 strcpy?
strcpy 函数将一个以 null 结尾的字符串从源复制到目标。它在 string.h 中声明,并接受两个参数:目标和源指针。strcpy 会一直复制直到遇到 null 终止符。它不检查缓冲区大小,因此可能不安全。对于安全性要求高的代码,请考虑使用 strncpy 或 strlcpy 进行边界检查复制。
strcpy 的基本用法
此示例演示了如何使用 strcpy 复制字符串。
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, World!";
char dest[20];
// Copy string including null terminator
strcpy(dest, src);
printf("Source: %s\n", src);
printf("Destination: %s\n", dest);
return 0;
}
在此,strcpy 将整个字符串从 src 复制到 dest,包括 null 终止符。目标缓冲区必须足够大才能容纳复制的字符串。当你知道目标大小时,这是一种复制字符串的简单方法。请务必确保目标有足够的空间以防止缓冲区溢出。
使用 strncpy 复制字符串
此示例演示了更安全的 strncpy 函数。
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "This is a long string";
char dest[10];
// Safe copy with length limit
strncpy(dest, src, sizeof(dest));
dest[sizeof(dest) - 1] = '\0'; // Ensure null termination
printf("Source: %s\n", src);
printf("Destination: %s\n", dest);
return 0;
}
strncpy 最多复制 n 个字符,从而防止缓冲区溢出。但是,如果源字符串过长,它可能不会以 null 终止字符串。我们手动添加 null 终止符以确保安全。这是处理固定大小缓冲区时推荐的方法。请始终将目标缓冲区大小指定为限制。
strcpy 的危险性
此示例演示了在未进行大小检查的情况下使用 strcpy 的危险性。
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "This string is definitely too long";
char dest[10];
// Unsafe copy - potential buffer overflow
strcpy(dest, src);
printf("Source: %s\n", src);
printf("Destination: %s\n", dest);
return 0;
}
此代码会导致缓冲区溢出,因为目标太小。行为是未定义的,可能会导致程序崩溃或产生安全漏洞。切勿在不信任的输入或未验证大小的情况下使用 strcpy。现代编译器可能会警告这种不安全的使用。在生产代码中始终优先使用有界字符串函数。
在不同内存位置之间复制
此示例展示了在动态分配的字符串之间进行复制。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *src = "Dynamic string";
char *dest = malloc(strlen(src) + 1); // +1 for null terminator
if (dest == NULL) {
printf("Memory allocation failed\n");
return 1;
}
strcpy(dest, src);
printf("Source: %s\n", src);
printf("Destination: %s\n", dest);
free(dest);
return 0;
}
在这里,我们为源字符串加上其 null 终止符分配了刚好足够的内存。strcpy 将字符串安全地复制到新位置。请务必检查 malloc 的返回值并释放已分配的内存。此模式在复制字符串时很常见。请注意,我们在分配之前计算了确切所需的空间。
复制部分字符串
此示例演示了复制字符串的一部分。
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Copy this part only";
char dest[10];
// Copy first 8 characters
strncpy(dest, src + 5, 8);
dest[8] = '\0'; // Ensure null termination
printf("Source: %s\n", src);
printf("Partial copy: %s\n", dest);
return 0;
}
我们使用指针算术跳过源字符串的前 5 个字符。strncpy 函数复制了 8 个字符。由于我们复制的是部分字符串,因此我们手动添加了 null 终止符。此技术对于提取子字符串很有用。在处理部分字符串时,请务必确保正确进行 null 终止。
字符串复制的最佳实践
- 优先使用 strncpy:尽可能始终使用长度受限的函数。
- 检查缓冲区大小:确保目标有足够的空间。
- 手动添加 null 终止符:在使用 strncpy 时,如有需要请手动添加 null 终止符。
- 避免使用 strcpy:切勿将 strcpy 用于不受信任的或可变长度的输入。
- 考虑 strlcpy:如果可用,strlcpy 比 strncpy 更安全。
来源
本教程涵盖了 strcpy 函数,从基本用法到高级注意事项。尽管字符串操作很简单,但需要谨慎处理,以防止程序中出现安全漏洞和未定义行为。
作者
列表 C 标准库。