Checking if a string is a palindrome This is the code for checking if a string is a palindrome. The execution time, for sample cases, is 0.40358 seconds. What must be done to increase the performance?

int main(){
    int c,flag = 0;
    char *ch, *h;
    ch = (char *)malloc(sizeof(char)*101);
    h = ch;
    while((c=getchar())!=EOF){
        *ch = c;
        ch++;
    }
    ch--;
    while(ch&gt;=h){
        if(*ch-- != *h++){flag = 1; break;}
    }
    flag == 1?(printf("NO")):(printf("YES"));
}


This is the code with an execution time of 0.4017 seconds for same test cases:

void main()
{
    char a[100],b[1000];
    int n,i,j=0,f=0;
    scanf("%s",a);
    n=strlen(a);
    for(i=n-1;i&gt;=0;i--)
    {
        b[j]=a[i];
        j++;
    }
    for(i=0;i&lt;n-1;i++)
    {
        if(a[i]==b[i])
        {
            f++;

        }
    }
    if(f==n-1)
    {
        printf("YES");
    }
    else
    {
        printf("NO");
    }
}


Why is the former slower than the latter? Are the library functions faster?
You can't really call a difference of 1% slower or faster. You should consider that both codes have exactly the same performance.

The only explanation for a speed difference between those two applications comes from the malloc (which is slightly slower than an array).

IMO, first code is better than second; the second one is quite hard to get (you are basically reversing a string, then comparing the reversed string with the normal one). I actually had to read the code 3 times to understand what was done.

About code review in itself:


First code sample:

You should indent your code in a consistent manner.

int c,flag = 0;
char *ch, *h;


Those variables are poorly named; flag could be replaced by is_palindromic, h could be string_start/str_start/str, and ch string_from_end/string_reverse etc....

while((c=getchar())!=EOF){


It's usually a good idea to separate comparators and equal sign from their operands, so it'd be something like this:

while((c = getchar()) != EOF){

Second code sample:

char a[100],b[1000];
int n,i,j=0,f=0;


Same as before, you should also avoid declaring 4 variables on the same line (especially considering you have both initialized and non-initialized variables).