I tried to reach out of the array's memory in my compare function. To my surprise, it works, however, I think there should be a memory error. Could someone have a look and give me an answer?
#include <stdio.h>
int string_compare(const char* w1, const char* w2, unsigned int len){
for(int i = 0; i < len; i++){
if(w1[i] != w2[i]){
return 0;
}
}
return 1;
}
int main(){
printf("%d\n",string_compare("Hello'\0' world!", "Hello",10));
}
There is no memory error.
Compare stops at index since
w1[5] != w2[5]is true.w1[5]is a', not a null character.Perhaps OP wanted to compare
"Hello\0 world!", "Hello"?Now that will have trouble with
index6, which is beyond"Hello"and incurs undefined behavior. "It works," might happen, might fail, It is UB.A proper string compare would stop when character differ or a null character is detected.