Understanding the Use of an Array of Characters Without Terminating Characters

Asked 2 years ago, Updated 2 years ago, 52 views

#include<stdio.h>
int main(void){
    char str[3];
    str[0] = 'a';
    str[1] = 'b';
    str[2] = 'c';
    printf("%s\n", str);
    return 0;
}

Run Results
abc

This code declares a char array str[3] with 'a' in str[0] and 'b'
in [1] contains 'c' in [2].
However, this string str does not have a termination '\0' and should not have the correct execution result, but this code returned abc.How did this program read the end of a string?

c

2022-09-29 22:23

3 Answers

The expectation that "you won't get the right results" is wrong.The code causes undefined behavior, and if it crashes, happens to show "abc", or The devil comes out of your nose, whatever happens.

While it is generally important (to avoid) to know what undefined behavior is, finding out why undefined behavior makes little sense.


2022-09-29 22:23

It just happened that the array was followed by a value equal to '\0', so it was determined to be terminated.
If you try this code, you'll find out.

printf("%d\n", str[3]);


2022-09-29 22:23

The compiler optimization process adjusts the array.

When we tried it, we found that it was abcL without optimization and abc with optimization (-O3).


2022-09-29 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.