c - 使用带有 char 指针的 strcat 函数

标签 c pointers string-literals strcat

<分区>

我想使用两个字符指针打印“Hello - World”,但我 有一个“段错误(核心转储)”的问题。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
int main()
{
  char* x="Hello";
  char* y="'World'";
  strcat(x, Hyphen);
  strcat(x, y);
  printf("%s",x);
  return 0;
}

最佳答案

您实质上是在尝试使用字符串文字作为 strcat() 的目标缓冲区.这是 UB有两个原因

  • 您正在尝试修改字符串文字。
  • 您正在尝试写入超过分配的内存。

解决方案:您需要定义一个数组,其长度足以容纳连接的字符串,并将其用作目标缓冲区。

通过更改代码的示例解决方案:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
#define ARR_SIZE 32    // define a constant as array dimention

int main(void)              //correct signature
{
  char x[ARR_SIZE]="Hello";   //define an array, and initialize with "Hello"
  char* y="'World'";

  strcat(x, Hyphen);          // the destination has enough space
  strcat(x, y);               // now also the destination has enough space

  printf("%s",x);            // no problem.

  return 0;
}

关于c - 使用带有 char 指针的 strcat 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55923281/

相关文章:

c - 为什么我可以修改C中的const指针?

c - 出现段错误时缓冲区溢出将不起作用

c - X11 如何使用 xcb 恢复/启动另一个应用程序窗口?

c++ - 需要使用 Book* head 变量重载运算符但不起作用

C++重载<<运算符问题

java - 创建新字符串作为文字/新对象时的内存分配

node.js - ECMAScript 2015 (ES6) 在 Node JS 上不带标志

c - c中倒带(文件偏移量)的实现

c - 无法知道段错误的原因

c - 传递给嵌套函数的字符串文字指针问题