quantum
quantum

Reputation: 1420

Strlen in Malloc

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

Answers (3)

xanatos
xanatos

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

Jay
Jay

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

Oliver Charlesworth
Oliver Charlesworth

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

Related Questions