I don't understand how there is uninitialised variable access in my code and stack buffer overflow even though the two strings are the same when debugging. When i add a null terminator to str2 it also does not fix the issue. When I use fgets the null terminator issue persists. How can i address this? And could someone explain why this is happening and what to look for when doing similar problems.
Note: code is checking if a string is a palindrome
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 4096
int main(void) {
// Handle taking in input
char str[MAX];
int len = 0;
while (scanf("%c", &str[len]) != EOF) {
len++;
}
char str_rev[MAX];
int j = 0;
for (int i = len-1; i >= 0; i--) {
str_rev[j] = str[i];
j++;
}
if (strcmp(str, str_rev) == 0) {
printf("String is a palindrome\n");
} else {
printf("String is not a palindrome\n");
}
return 0;
}
Error: stack buffer overflow.
Values when execution stopped:
j = 7
len = 7
str = "racecar", <4089 uninitialized values>
str_rev = "racecar", <4089 uninitialized values>
str_rev[j] = <uninitialized value>
To use strcmp
both arrays must be C-strings. So, both must have the nul-terminator at the end.
You have to add
str[len] = 0;
str_rev[len] = 0;
before the call to strcmp
.
complete example: https://godbolt.org/z/GGKKdPoPc
As a side note: Your code has a problem when someone enters ABA<enter>
, as it will also read the Enter, so str_rev
will be "\nABA"
.