How can I write this C fragment more safely?

I have the following C code snippet and should identify the error and suggest a way to write more securely:

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 end line '\0'for the line, and so there won't be enough memory allocated for the copy, but I'm not sure if they are going to write about it more safely?

I could just use malloc(strlen(somestring)+1))I suppose, but I think there should be a better way than this?


EDIT: OK, I accepted the answer, I suspect that strdup's solution is not expected from us, because it is not part of ANSI C. This seems to be a rather subjective question, so I'm not sure what I accepted is actually the best . Thanks everyone for the answers.

+5
source share
10 answers
char   somestring[] = "Send money!\n";
char   *copy;
size_t copysize;

copysize = strlen(somestring)+1;
copy = (char *) malloc(copysize);
if (copy == NULL)
    bail("Oh noes!\n");

strncpy(copy, somestring, copysize);
printf("%s", copy);

The noted differences above:

  • It is necessary to check the result malloc()!
  • Calculate and save memory size!
  • Use strncpy()because strcpy()naughty. In this far-fetched example, this does not hurt, but does not get used to using it.

EDIT:

, , strdup()..., , . , :

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

, , .

+4

, strncpy, :

printf(string)

:

printf("%s", string);

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

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

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

xstrdup:

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

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

    return copy;
}
+6
  • strlen + 1, \0
  • malloc ; malloc
+3

Ick... strdup(), , , . ... 25 , , printf(copy) . malloc(strlen(str)) , , , - - "%s%n"...

+3

, . strncpy , strcpy ( ). memcpy < string.h > , . , , C.

:

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

copysize = strlen(somestring)+1;
copy = (char *) malloc(copysize);
if (copy == NULL)
    bail("Oh noes!\n");

memcpy(copy, somestring, copysize); /* You don't use str* functions for this! */
printf("%s", copy);
+1

( ).

  • . , somestring. .
  • , ( strdup, ). .
  • .
  • .
  • malloc.
  • malloc.
  • printf . printf("%s", copy) puts(copy).
  • - , .
+1

Adrian McCarthy ,

,

+1

, - , Ada.

somestring : constant string := "Send money!";
declare
   copy : constant string := somestring;
begin
   put_line (somestring);
end;

, ?

  • ( ). .
  • - , .
  • , , C, - , , , strlen().

, "" Ada - . . Ada , .

0

strncpy strcpy. : . ANSI C, ( , POSIX).

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

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

strncpy(copy, somestring, strlen(somestring));
printf(copy);
-2

All Articles