This was a piece of code I have written for my assignment, some of the weird code design are not controllable by me. I am currently writing these on MacOS.
file1
#include <stdio.h> extern int read_palindrome(); int main() { if (read_palindrome()) printf("input is a palindrome"); else printf("input is not a palindrome"); return 0; } file2
#include <stdio.h> #include <stdlib.h> #include <string.h> int check_palindrome2(char *, int); // malloc() will be used as usual to set aside an initial memory // The entire input will be read gradually by characters using getchar() // In the event we require more memory than what we have previously, // use realloc() to increase memory size dynamically int read_palindrome() { unsigned int len_max = 128; unsigned int current_size = 0; char *pStr = malloc(len_max); current_size = len_max; int i = 0; int c = EOF; if (pStr == NULL) { return -1; } while (( c = getchar() ) != '\n') { pStr[i] = (char)c; i++; if(i == current_size) { current_size += len_max; char *tmp = realloc(pStr, current_size); if (tmp == NULL) { free(pStr); return -1; } pStr = tmp; } } int retval = check_palindrome2(pStr,i); free(pStr); return retval; } int check_palindrome2(char *s, int length) { for (int i = 0; i < length / 2; i++) { if (s[i] != s[length-i-1]) return 0; } return 1; } I would think this code works except for empty files, which will cause my program to continuously expect input and not terminate. However, I realised when using Sublime Text, creating a test.in file without pressing "Enter" somehow displays the "non-terminating" behaviour as well, while typing something in vim without pressing "Enter" for a newline still allows the code to work. Does anyone know the reason behind this phenomenon?
while (( c = getchar() ) != '\n' && c!=EOF)