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.
source
share