Not null-terminating a C-style string

后端 未结 6 2074
萌比男神i
萌比男神i 2021-01-24 12:08

Given a string , say ,

char *str = \"Hello,StackOverflow!\"
char newStr[30];
int l = strlen(str);
for(int i =0 ; i

        
相关标签:
6条回答
  • 2021-01-24 12:23

    The behaviour of reading bytes that have not been initialized as characters is undefined in most implementations of C. Sometimes printf may write garbage, sometimes the program may find a null byte \0 after the last character and terminate normally. In some rare cases it may cause a crash. This is why you are seeing variation in what happens when you run the program. It depends on the compiler you are using, and what was in the memory location following that which you are allocating for the array.

    (That is, if your program would compile - you've left off a semicolon)

    0 讨论(0)
  • 2021-01-24 12:27

    I would suspect that most of the time it would keep printing past the "!" and keep going in memory until it hits a NULL. Which could result in a crash, but doesn't have to.

    This is why it's best to either:

    memset(newStr, 0, 30);
    

    or

    // This works because string literals guarantee a '\0' is present
    // but the strlen returns everything up until the '\0'
    int l = strlen(str) + 1;
    

    this works too, but I don't feel it's as clear as adding one to strlen:

    for(i =0 ; i<=l ; i ++ )
    

    As the defination of strlen implies you need to.

    0 讨论(0)
  • 2021-01-24 12:28

    Your program has undefined behaviour, since you promise to call printf with a pointer to a null-terminated string but fail to do so. Anything could happen, but your program is simply not correct.

    Specifically, while reading the array elements one by one to find the null terminator, the program will eventually access an uninitialized variable, which is UB.

    0 讨论(0)
  • 2021-01-24 12:38

    A "crash" is not guaranteed. A program that improperly handles null terminators in strings - more generally accesses data outside of buffer boundaries - or violates the printf format string, may seem to work just fine, functioning and not e.g. causing a segfault. But this is just happenstance: the behavior of your code is undefined.

    It will be the same in C++.

    0 讨论(0)
  • 2021-01-24 12:38

    By chance, most of the time the uninitialized bytes in newStr happen to be 0 in your particular case.

    0 讨论(0)
  • 2021-01-24 12:50

    No. It invokes undefined behavior - it means it doesn't have to crash - it can do literally anything, like nasal demons.

    Also, "gives a runtime error" - well, that depends on what do you mean by a runtime error. There's no dynamic runtime for C - if you expect a nicely formatted error message from an exception, that wouldn't happen. What would happen is most likely a segmentation fault.

    All in all, if one causes/uses undefined behavior, he must not rely on it crashing or not crashing.

    0 讨论(0)
提交回复
热议问题