c - strcat() 函数实际上是如何工作的及其替代方法

标签 c dynamic-memory-allocation c-strings strcat

让我们举个例子。

#include <stdio.h>
#include <string.h>

int main() {
    char str1[7] = "hello ";
    printf("Initial size of str1 is: %d\n", strlen(str1));
    char str2[] = "buddy";
    printf("%s\n", strcat(str1, str2));
    printf("Final size: %d\n", strlen(str1));
}

上述程序的输出将是

Initial size of str1 is: 6
hello buddy
Final size: 11

--------------------------------
Process exited after 0.835 seconds with return value 0
Press any key to continue . . .

看到了吗? str1 的大小如何从 7 变为 11(包括 null 变量),关于我认为会发生的事情是:

  • 一些我不知道的函数可能已经为 str1 从与以前相同的地址开始重新分配了连续内存,即 str1 大小为 strlen(str1)+strlen( str2)+1 +1 为空值,然后重新定义它得到hello buddy

如果我错了,请告诉我,如果不是,那它是什么功能,它是如何工作的?

还有一个问题:如何在不使用 strcat 函数的情况下编写代码来完成上述任务。

我尝试使用 realloc() 来做,但没有完全成功,可能是因为 realloc() 只能重新分配动态分配的内存,是这样吗?

最佳答案

缓冲区溢出

OP 的代码失败,因为 strcat(str1,str2) 试图写入超过 str1[] 的结尾 - 结果:未定义的行为 ( UB)。 @dimich

改为使用更大的目标缓冲区。

// char str1[7]="hello ";
char str1[7 + 5]="hello ";
char str2[]="buddy";
printf("%s\n",strcat(str1,str2));

使用正确的打印说明符

strlen() 返回一个 size_t,而不是一个 int

// printf("Initial size of str1 is: %d\n",strlen(str1));
printf("Initial size of str1 is: %zu\n",strlen(str1));

提示:启用所有警告。

备选

许多备选方案之一:将 str2 复制到 str1 的末尾。

// printf("%s\n",strcat(str1,str2));
strcpy(str1 + strlen(str1), strt2);
printf("%s\n",str1);

realloc()

realloc() can only reallocate dynamically allocated memory, is it so?

realloc() 不应用于指向未分配、非NULL 指针的指针。
除了重新分配动态分配的内存之外,realloc() 可以在没有预先分配的情况下启动。

char *p = realloc(NULL, size);
// just like
char *p = malloc(size);

故事的寓意

  • 注意string 函数的内存使用情况。
  • 启用所有警告。

关于c - strcat() 函数实际上是如何工作的及其替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73204284/

相关文章:

矩阵的 c 函数 free()

c++ - inportb() 和 inport() 函数有什么区别?

c - libjpeg-turbo-1.5.1-vc.exe 中的 TurboJPEG API 产生错误的输出

c++ - 在 c++ 中创建父类(super class)类型的数组以动态存储子类对象

c - 为什么在写入使用字符串文字初始化的 "char *s"而不是 "char s[]"时出现段错误?

c++ - 输入 2 个非常基本的 C 字符串时无限循环

c - 为什么我们使用线程并一起选择

java - 当使用 new-operator 调用堆中的 Class() 进行多次调用时会发生什么?

c - Visual Studio 动态分配多维数组

对字符串的 C 指针操作会产生意外的输出