gpt4 book ai didi

c - 字符串指针和strcpy

转载 作者:行者123 更新时间:2023-11-30 20:21:17 24 4
gpt4 key购买 nike

为什么这个程序会出现段错误

int main()
{
char *ptr;
ptr = (char *)malloc(15*sizeof(char));
ptr = "string";
strcpy(ptr,"NewString");
}

虽然这不是

int main()
{
char *ptr;
ptr = (char *)malloc(15*sizeof(char));
strcpy(ptr,"String");
ptr = "Newstring";
}

或者当要修改字符串中的一个文字时类似的程序

int main()
{
char *ptr;
ptr = "string";
ptr[1] = 's';
}

当这没有发生时

int main()
{
char *ptr;
ptr = (char *)malloc(15*sizeof(char));
strcpy(ptr,"String");
ptr[1] = 's';
}

最佳答案

以上所有情况都会导致 undefined behavior

为了便于解释,我们将这四个片段按照出现的顺序分别称为(I)、(II)、(III)和(IV)。

  • 因此,在 (I) 中,strcpy(ptr,"String"); 是尝试写入不可写内存(尝试修改字符串文字,换句话说)。

  • 在 (II) 中,strcpy(ptr,"String"); 会导致内存溢出,因为目标空间小于源空间。

  • 在 (III) 中,ptr[1] = 's'; 尝试修改字符串文字(部分)。

  • 在(IV)中,与(II)相同。

你无法解释导致 UB 的程序的结果。段错误是 UB 的众多可能的副作用之一不是唯一的副作用

也就是说,please see this discussion on why not to cast the return value of malloc() and family in C. .

关于c - 字符串指针和strcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43233062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com