Corneille K
Corneille K

Reputation: 73

I don't understand the result of this little program

i've made this little program to test a little part of a bigger program.

    int main()
{
    char c[]="ddddddddddddd";
    char *g= malloc(4*sizeof(char));
    *g=NULL;
    strcpy (g,c);

    printf("Hello world %s!\n",g);
    return 0;
}

I expected that the function would return "Hello World dddd" ,since the length of g is 4*sizeof(char), but it returns " Hello World ddddddddddddd ".Can you explain me Where I'm wrong ?

Upvotes: 0

Views: 27

Answers (1)

paxdiablo
paxdiablo

Reputation: 881293

Don't do that, it's undefined behaviour.

The strcpy function will happily copy all those characters in c regardless of the size of g.

That's because it copies characters up to the first \0 in c. In this particular case it may corrupt your heap, or it may not, depending on the minimum size of things that get allocated in the heap (many have a "resolution" of sixteen bytes for example).

There are other functions you can use (though they're optional) if you want your code to be more robust, such as strncpy (provided you understand the limitations), or strcpy_s(), as detailed in Appendix K of the ISO C11 standard (and earlier iterations as well).

Or, if you can't use those for some reason, it's up to the developer to ensure they don't break the rules.

Upvotes: 1

Related Questions