0

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?

7
  • Maybe vim automatically adds a line terminator for the last line of a file? Commented Feb 1, 2019 at 14:57
  • 2
    And it should be: while (( c = getchar() ) != '\n' && c!=EOF) Commented Feb 1, 2019 at 14:59
  • @PaulOgilvie Oh sorry, this was the version of my code before I included EOF to handle the empty files and the Sublime Text problem case. So I take it that you are not sure of the weird behaviour too? Commented Feb 1, 2019 at 15:24
  • It is not weird behavior of SubLime. If the user does not want to terminate the last line of a file with a newline, then that is his choice and may be intentional and/or required for some purpose. Commented Feb 1, 2019 at 15:36
  • Then do you know why vim might possibly "automatically add a line terminator"? Commented Feb 1, 2019 at 15:40

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.