gpt4 book ai didi

c - 为什么 strcpy 向变量复制的字符比预期的多?

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

我目前正在处理大量的 strcpy' 和 calloc's。然后我听说strncpy使用起来更安全。所以我所做的就是创建一个处理 strcpy 的函数..如下所示。

void safeStrncpy(char * dest, char * src){
//copy string
if(sizeof(dest) >= strlen(src) + 1){
strncpy(dest, src, strlen(src));
}else{
if(realloc(dest, (strlen(src)) + 1) == NULL){
printf("error");
}else{
strncpy(dest, src, strlen(src));
}
}
}

您会注意到我使用了 sizeof(dest) 。我真正想做的就是获取分配给 dest 的内存大小,这样我就知道何时使用 realloc。但后来我了解到你无法获得分配给 dest 的内存大小,所以我想到了一个解决方法。

char * l = calloc(10,sizeof(char));
printf("%s", strcpy(l,"asdfghjkldfghasdfghjkl"));

上面显示的代码将 10 个项目分配给指针 l。我认为如果我这样做并复制了比分配的字符更多的字符,它只会复制适合大小的字符。我期望 l 的值是“asdfghjkld”。但令我惊讶的是,事实并非如此。它复制了整个字符串,即“asdfghjkldfghasdfghjkl”。

现在,如果 calloc 会被覆盖,为什么还要使用 calloc 呢?在 char 指针声明、内存分配和 strcpy 期间后台发生了什么? c会自动重新分配内存吗?我是否需要担心这种行为,也许是安全问题?

最佳答案

你问:

why does strcpy copies more character to the variable than it is supposed to?

documentation of strcpy :

Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.

它没有指定如果目标长度不足以包含源,程序应如何运行。最有可能的是,您的实现只是写入了超出范围的内存,这将导致未定义的行为。

这是一个可能的解决方案。

  1. 创建一个包含 char* 和大小的 struct

    typedef struct _MyString
    {
    char* data;
    size_t size;
    } MyString;
  2. safeStrncpy中使用它

    void safeStrncpy(MyString* dest, char * src){
    if(dest->size < strlen(src) + 1){
    dest->size = strlen(src)+1;
    dest->data = realloc(dest->data, dest->size);
    }
    strcpy(dest->data, src);
    }

关于c - 为什么 strcpy 向变量复制的字符比预期的多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589128/

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