简体   繁体   中英

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 ?

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. 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 . Then you write to that location using memcpy . In contrast to previous example you can write/modify content at this location. But you need to free this memory later.

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. Use strcpy instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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