本文介绍了C:“ zsh:中止”;错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的程序:

#include <stdio.h>

char    *ft_strcat(char *dest, char *src)
{
    int i;
    int k;

    i = 0;
    k = 0;
    while (dest[i])
        i++;
    while (src[k])
    {
        dest[i + k] = src[k];
        //i++;
        k++;
    }
    dest[i + k] = '\0';
    return (dest);
}

int main(){
    //ft_strcat
    char str[] = "Hello, ";
    char str2[] = "World!";
    printf("%s", ft_strcat(str, str2));
    return 0;
}

它实现了strcat功能。
当我尝试复制世界!时到你好,我有一个错误 zsh:中止。尝试复制到 Hello时没有问题。

It's implementing of strcat function.When I'm trying to copy "World!" to "Hello, " I have an error "zsh: abort". There's no problem when I'm trying to copy to "Hello ".

该错误该怎么办?为什么此逗号会引起此问题?

What can I do with this error? Why this comma causes this problem?

推荐答案

定义空维度数组并使用括号括起来的初始化程序列表进行初始化时,数组的大小由提供的初始化程序列表元素确定。

When you define an array with empty dimension and initialize that with a brace-enclosed initializer list, the size of the array is determined by the supplied initializer list elements.

因此,在您的情况下为 str str2 的长度刚好足以容纳字符串 你好, 世界!

So, in your case, str and str2 are just long enough to hold the strings "Hello, " and "World!", respectively.

所以,这里的问题是目标缓冲区(作为 ft_strcat()的第一个参数传递)绝对没有空间容纳 concatenated 结果。您正在访问内存不足,从而导致。

So, the problem here is, the destination buffer (passed as the first argument of ft_strcat()) has absolutely no space to hold the concatenated result. You're accessing out of bound memory, thus causing undefined behavior.

while 循环的第一个迭代中,

In the very first iteration of the while loop,

while (src[k])
    {
        dest[i + k] = src[k];
        //i++;
        k++;
    }

索引 i + k 指向目的地的内存不足。很快,您尝试使用索引访问内存位置就遇到了UB。

the index i+k points to out of bound memory for dest. No sooner than you try to use the index to access the memory location, you face UB.

您需要确保目标位置有足够的空间来容纳级联对象结果。为此,您可以采用两种方法之一

You need to make sure, the destination has enough space left to hold the concatenated result. For that, you can have either of two approaches


  • 静态定义更大的数组大小并将其用作目标。在这种情况下,您始终可以轻松地检查实际大小与已经使用的大小,因为这是一个字符类型数组,旨在用作 string 提示: sizeof vs strlen() )。

  • 您可以使用指针,使用内存分配器函数分配一定数量的内存,并根据需要分配 realloc()

  • Define a bigger array size statically and use that as destination. You can always check for the actual size vs. already used size easily in this case, as this is a character type array meant to be used as string (hint: sizeof vs strlen()).
  • You can make use of a pointer, use memory allocator function to allocate certain amount of memory and realloc() as needed.

这篇关于C:“ zsh:中止”;错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:57