【问题标题】:Why is malloc giving wrong string , when while working? [duplicate]为什么 malloc 在工作时给出错误的字符串? [复制]
【发布时间】:2021-11-16 18:46:35
【问题描述】:
char* my_strdup(char* param_1){
    char *p;
    int n = sizeof(param_1);

    p = (char*)(malloc(sizeof(char)*n));
    int i = 0;
    while(i<n){
        p[i] = param_1[i];
        i++;
       
    }
    return p;

}

while 最终没有被破坏 我该如何解决

enter image description here

【问题讨论】:

  • sizeof (param_1)更改为strlen(param_1) + 1,这是字符串的实际长度(包括NUL '\0'),而不是char *的大小。作为旁注,请将param_1 改为const char *,因为您没有修改它。
  • 欢迎来到 SO。 malloc 根本不提供任何字符串。它只是返回一个地址。而且您使用了错误的大小进行分配。 sizeof param_1 只会产生指针的大小,这可能不是您想要的。

标签: c malloc


【解决方案1】:

sizeof(T) 给出类型 T 的对象所需的内存量。如果 T 是变量,则使用该变量的类型。

对于char* param_1,表达式sizeof(param_1) 为您提供char* 类型所需的内存,即指针的大小。这可能总是8(指针在 64 位机器上所需的大小)。但绝对不是param_1指向的字符串长度。

正确的是……

int n = strlen(param_1) + 1;

+ 1 是必需的,因为每个字符串的末尾都需要一个额外的终止字符。 +1,与实际内容一起复制。

【讨论】:

    猜你喜欢
    • 2021-04-13
    • 2023-03-31
    • 1970-01-01
    • 2016-12-07
    • 2018-10-02
    • 1970-01-01
    • 2015-06-05
    • 2021-11-25
    • 2015-04-03
    相关资源
    最近更新 更多