Reputation: 1420
Why does this return no warnings? What is supposed to be wrong with the code?
char *str = malloc(strlen("hello" + 1));
strcpy(str, "hello");
Thanks!
Upvotes: 4
Views: 12740
Reputation: 111860
This
char *str = malloc(strlen("hello" + 1));
strcpy(str, "hello");
is nearly equivalent to:
char *temp = "hello";
char *temp2 = temp + 1;
char *str = malloc(strlen(temp2));
strcpy(str, "hello");
so temp + 1
is pointer math (it returns a pointer to ello
, and strcpy
doesn't check if enough memory is present at destination ("standard" memory corruption caused by faulty code in C)
The end result is that strlen
returns 4, strcpy
uses 6 bytes of memory and a random piece of heap is trashed.
Upvotes: 6
Reputation: 24895
The below statement is incorrect.
char *str = malloc(strlen("hello" + 1));
It should be
char *str = malloc(strlen("hello") + 1);
strlen in this case would probably return you a value of 4 instead of 5 and strcpy will lead to Out of Bounds write. Execute the program with a memory analyzer and it shall point out an error to you.
Upvotes: 1
Reputation: 272487
Why would you expect warnings?
The code is broken because you should be doing strlen("hello") + 1
, not strlen("hello" + 1)
(which is equivalent to strlen("ello")
).
Upvotes: 9