I have a task to write the function:
int read_palindrome(); // input comes from stdin
which will read one line from standard input and returns 1 if the line is a palindrome and 0 otherwise. A line is terminated by the newline character (ā\nā) and the does not include the newline.
There are requirements to be met:
There is no assumption about the length of the input. You are also not allowed to read the input twice, e.g. read the input, forget you read the input but remember the length, read the input again. which results in the input being read twice.
You are also not allowed to create a very large buffer to store the input reasoning that the input line might be expected to be smaller than a very large buffer. The reason for this restriction is that we will consider the memory usage of the program.
The task is to come out with a correct program with the best CPU time and memory usage.
I have attempted my code below. May I know if there is anything I could improve on here to optimise for correctness, CPU and memory?
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int read_palindrome();
int check_palindrome2(char *, int);
int main()
{
if (read_palindrome()) printf("input is a palindrome");
else printf("input is not a palindrome");
return 0;
}
int read_palindrome() {
unsigned int len_max = 128;
unsigned int current_size = 0;
char *pStr = malloc(len_max);
current_size = len_max;
int i;
char c;
if (pStr != NULL) {
while (( c = getchar() ) != '\n') {
pStr[i] = (char)c;
i++;
if(i == current_size) {
current_size = i+len_max;
pStr = realloc(pStr, current_size);
}
}
pStr[i] = '\0';
free(pStr);
}
return check_palindrome2(pStr,i);
}
int check_palindrome2(char *s, int length) {
for (int i = 0; i < length; i++) {
if (s[i]!= s[length-i-1]) {
return 0;
}
}
return 1;
}
check_palindrome2()
, you only need to perform the comparison untillength/2
\$\endgroup\$ – Damien Jan 30 '19 at 14:46fgets()
may be more efficient. To be tested. \$\endgroup\$ – Damien Jan 30 '19 at 15:02