Question

The two following codes are similar but the first has a structure, the second not.

Why this code works (with no warnings)?

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

struct prova
{
    char *stringa;
};

int main()
{
    struct prova p;

    strcpy (p.stringa, "example\0");

    printf("%s\n", p.stringa);

    return 0;
}

But the following code doesn't work?

Segmentation fault (core dumped)

With this warning:

code.c: In function ‘main’: code.c:8:9: warning: ‘stringa’ is used uninitialized in this function [-Wuninitialized] strcpy (stringa, "example\0");

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

int main()
{
    char *stringa;

    strcpy (stringa, "example\0");

    printf("%s\n", stringa);

    return 0;
}

Thank you!

Was it helpful?

Solution

Neither is correct because you copy to an address specified by an uninitialized variable. Therefore both programs invoke undefined behaviour.

The fact that one of the programs works is down to pure chance. One possible form of undefined behaviour is that your program runs correctly.

You need to initialize the pointer to refer to a sufficiently sized block of memory. For instance:

char *stringa = malloc(8);

Note that you do not need to add a null terminator to a string literal. That is implicit. So, given this memory allocation you can then write:

strcpy(stringa, "example");

OTHER TIPS

You need to give the string some memory for it copy the characters to.

Use malloc

besides the first example does not compile.

When you write

struct prova { char *stringa; };

int main() { struct prova p;

strcpy (p.stringa, "example\0");

notice that p.stringa points to nowhere in particular but you copy to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top