简体   繁体   中英

strcpy vs direct assignment: Overflow issue

This is a practice question from my school, it's not a homework question:

Given the following declaration, write a snippet of C code that might lead to strlen(arr) returning no less than 8.

 char arr[4]; 

My attempt to this question is: impossible, there is no way to achieve this. Since strlen will return the number of chars in an char array until it meets the first \\0, I don't see there is anyway we can let strlen return 8 in this case. I think if we force to assign a 8-length-long string to this array, the behavior is not predictable.

However, the solution that our instructor gives is the:

strcpy(arr, Any 8-char-long string);

For example:

strcpy(arr, "Overflow");

I don't understand why this is valid, in my understanding, I don't see this array has enough space to hold this 8-length string, is there something I miss for understanding the string in C?

"Given the following declaration, write a snippet of C code that might lead to strlen(arr) returning no less than 8."

That is not possible, since arr can only hold 3 characters and 1 null terminator.

My attempt to this question is: impossible, there is no way to achieve this

Correct.

However, the solution that our instructor gives is the: strcpy(arr, Any 8-char-long string);

Your instructor is incompetent and shouldn't be teaching C. This will write out of bounds of the array and anything can happen, including program crashes or the program seeming to work as intended this time of execution .

I don't understand why this is valid

It is not, it invokes undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM