简体   繁体   English

带/不带malloc的C字符指针

[英]C char pointer with/without malloc

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
    const char *str = "This is a string";
    char *strCpy = strdup(str); // new copy with malloc in background

    printf("str: %s strCpy: %s\n", str, strCpy);
    free(strCpy);

    char *anotherStr = "This is another string";
    printf("anotherStr: %s\n", anotherStr);

    char *dynamicStr = malloc(sizeof(char) * 32);
    memcpy(dynamicStr, "test", 4+1); // length + '\0'
    printf("dynamicStr: %s\n", dynamicStr);
    free(dynamicStr);

    return 0;
}

Why is the definition of anotherStr without malloc also possible, and what are the differences between anotherStr and dynamicStr ? 为什么没有malloc的anotherStr定义也是可能的, anotherStrdynamicStr什么dynamicStr

It is possible because here: 可能是因为这里:

char *anotherStr = "This is another string";

The string literal("This is another string") is allocated somewhere else, and anotherStr is merely set to point to that area in memory. 字符串常量(“ This is another string”)被分配在其他位置,并且anotherStr仅设置为指向内存中的该区域。 You can't change this string for example. 例如,您不能更改此字符串。 More here 这里更多

Here: 这里:

char *dynamicStr = malloc(sizeof(char) * 32);
memcpy(dynamicStr, "test", 4);

Memory of given size is allocated somewhere and pointer to it is returned which is assigned to dynamicStr . 给定大小的内存分配在某个地方,并返回指向它的指针,该指针分配给dynamicStr Then you write to that location using memcpy . 然后,您使用memcpy写入该位置。 In contrast to previous example you can write/modify content at this location. 与之前的示例相反,您可以在此位置写入/修改内容。 But you need to free this memory later. 但是您需要稍后释放此内存。

ps. PS。 In above example you trigger Undefined Behaviour when printing because you used memcpy for copying and copied 4 characters - and forgot to copy null terminator too. 在上面的示例中,您在打印时触发了“未定义行为”,因为您使用memcpy进行了复制并复制了4个字符-并且也忘记了复制空终止符。 Use strcpy instead. 请改用strcpy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM