in Programming in C
284 views
0 votes
0 votes

The following program seg-faults (crashes) when user supplies input as ‘freeze’ while it works fine with input ‘zebra’. Why?

#include<stdio.h>
int main(int argc, char *argv[])
{
    char *ptr = (char*)malloc(10);
    if(NULL == ptr)
    {
        printf("\n Malloc failed \n");
        return -1;
    }
    else if(argc == 1)
    {
        printf("\n Usage  \n");
    }
    else
    {
        memset(ptr, 0, 10);
        strncpy(ptr, argv[1], 9);
        while(*ptr != 'z')
        {
            if(*ptr == '')
                break;
            else
                ptr++;
        }
        if(*ptr == 'z')
        {
            printf("\n String contains 'z'\n");
            // Do some more processing
        }
       free(ptr);
    }
    return 0;
}
in Programming in C
284 views

1 Answer

4 votes
4 votes
Best answer
The problem here is that the code changes the address in ‘ptr’ (by incrementing the ‘ptr’) inside the while loop. Now when ‘zebra’ is supplied as input, the while loop terminates before executing even once and so the argument passed to free() is the same address as given by malloc(). But in case of ‘freeze’ the address held by ptr is updated inside the while loop and hence incorrect address is passed to free() which causes the seg-fault or crash.

This question and solution is available at internet. before posting any questions please search on the google first. If you could not get solution or if you could not understand the solution or if you think its really good  questions then and only then post. By the way it was a good que Thx.
selected by
by

1 comment

thanks
0
0

Related questions