Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could this C fragment be written more safely?

I have the following C code fragment and have to identify the error and suggest a way of writing it more safely:

char somestring[] = "Send money!\n";
char *copy;

copy = (char *) malloc(strlen(somestring));

strcpy(copy, somestring);
printf(copy);

So the error is that strlen ignores the trailing '\0' of a string and therefore it is not going to be allocated enough memory for the copy but I'm not sure what they're getting at about writing it more safely?

I could just use malloc(strlen(somestring)+1)) I assume but I'm thinking there must be a better way than that?


EDIT: OK, I've accepted an answer, I suspect that the strdup solution would not be expected from us as it's not part of ANSI C. It seems to be quite a subjective question so I'm not sure if what I've accepted is actually the best. Thanks anyway for all the answers.

like image 659
Adam Taylor Avatar asked May 26 '09 16:05

Adam Taylor


2 Answers

I can't comment on the responses above, but in addition to checking the return code and using strncpy, you should never do:

printf(string)

But use:

printf("%s", string);

ref: http://en.wikipedia.org/wiki/Format_string_attack

like image 147
Sucuri Avatar answered Oct 07 '22 21:10

Sucuri


char somestring[] = "Send money!\n";
char *copy = strdup(something);

if (copy == NULL) {
    // error
}

or just put this logic in a separate function xstrdup:

char * xstrdup(const char *src) 
{
    char *copy = strdup(src);

    if (copy == NULL) {
       abort();
    }

    return copy;
}
like image 44
dfa Avatar answered Oct 07 '22 22:10

dfa