2
char imei_temp[14] = {0, };

strcpy(imei_temp, "00000000000000");

According to my understanding this is valid code.

But Klocwork is saying Buffer overflow, array index of 'imei_temp' may be out of bounds. Array 'imei_temp' of size 14 may use index value(s) 0..14

1
  • "size 14 may use index value(s) 0..14" -> very common incorrect assumption. Valid indices are 0..13. Commented Jun 21, 2012 at 2:03

2 Answers 2

13

It's a buffer overflow because your buffer is 14 bytes, but you are writing 15 bytes to it: 14 ascii "0"'s, and a null byte at the end.

Sign up to request clarification or add additional context in comments.

1 Comment

"To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source."
3

when you specify a string using "s it adds an implicit \0 to the end of the string, you're trying to copy 15 bytes in to a 14 byte buffer.

Note, this doesn't happen when you specify a character using 's.

10 Comments

It's not specifying with ", it's strcpy appending the NUL byte which is the issue.
strcpy does not append a NUL. strcpy will copy characters from a memory location until it finds a NUL. This means practically that if you specify a memory location that is not a string it is possible that a very large number of characters are copied until a NUL is found. But strcpy has no mechanism for appending a NUL. The "s are adding the NUL byte, you can prove this to yourself by dumping a string into a char array and printf("%d", array[i]) in a for loop for the entire array.
Thanks for the answer, But as you said it will only copy 14 bytes, not the null terminated character. So the code should be valid.
@OmnipotentEntity: I never said that using " doesn't have append a NUL to the memory, but my point is that strcpy will copy and include the NUL. I think we're possibly saying the same thing in different ways. My point in saying "It's not specifying with "" is that it's strcpy's behaviour which is ultimately responsible for 15 bytes being copied. (e.g. you could use strncpy and avoid this)
@Len, strcpy will copy and include the NUL. " includes a NUL (if it didn't potentially many more bytes would be copied than just 14+1). We are saying the same thing, just talking past each other. @shunty, I did not say it would only copy 14 bytes. It will copy 15 bytes. All 14 0s and then a NUL. (\0)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.