Search code examples
cstringstrcmp

Initializing a string with the empty string


I was wondering if it is possible to initialize a string with an empty string like this:

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

char* some_function() {
    char* w = malloc(100*sizeof(char));
    w = "";
    if (1 == 2) {
        w = "Not empty anymore";
    }
    return w;
}

int main(void) {

    char* word = some_function();
    int r = strcmp("", word);

    printf("%s\n", word);
    printf("%d\n", r);
    return 0;
}

It compiles fine and gives me the result I want, however I'm still quite new at C and was wondering if this would lead to any problems down the line. Also is my use of strcmp to compare word to "" ok?


Solution

  • Well it's sort of possible, but it won't behave the way you expect. And in more recent versions of C, it's undefined behaviour.

    What you did was allocate memory and then throw that pointer away, thus leaking that memory. You replaced the pointer with a non-constant pointer to a string literal (which should make your compiler emit a warning or an error).

    This happened to work in your case. Fortunately you didn't try to write to that memory. If you did, chances are that bad stuff will happen.