4
#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?

1

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thx. So char *anotherStr = "..."; have the same behaviour as const char *str = "...";?
@leon22: I believe so yes, please also check link I provided.
@leon22 so long as you don't try to write to the characters, yes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.