Why do we get a segmentation fault while performing any operation on an uninitialized pointer ?

[HASHTAG]#include[/HASHTAG]
[HASHTAG]#include[/HASHTAG]
int main(void)
{
char *p ;
strcat(p, "abc");
printf("\n %s \n", p);
return 0;
}

If I print this the value at some random location pointed to by pointer , I get some garbage value so then there must be some compile-time error rather than segmentation fault ,plz clarify this .

Replies

  • Vishal Sharma
    Vishal Sharma
    radha gogia
    [HASHTAG]#include[/HASHTAG]
    [HASHTAG]#include[/HASHTAG]
    int main(void)
    {
    char *p ;
    strcat(p, "abc");
    printf("\n %s \n", p);
    return 0;
    }

    If I print this the value at some random location pointed to by pointer , I get some garbage value so then there must be some compile-time error rather than segmentation fault ,plz clarify this .
    This might be a brain fart but you missed stdio header (you are using printf).

    Coming to the question.
    You have not allocated any space for *p and you are trying to store something. hence, the segmentation fault. However, for this program, even if you allocate some space, you'll see some crap at the start followed by the string you are concatenating. Program with allocated space. Execute it, and check me on the output.

    #include
    #include
    #include
    int main(void)
    {
    char *p = (char *)malloc(1024);
    strcat(p, "abc");
    printf("\n %s \n", p);
    return 0;
    }
    

You are reading an archived discussion.

Related Posts

Quote: We invite cartoons which humorously communicate the seriousness of the theme, by rethinking sustainability with respect to water in terms of conservation, preservation and recycling. Rethink situations, rethink water,...
Once in a while a major gadget manufacturer decides to launch a product in India ahead of other nations. This time around LG Electronics, the South Korean electronics company, decided...
i am new b.tech. student in iit roorkee in metrology and metals. i want to became a reseacher what i want to do?
Have you ever been in a situation where you want to quit your 9-to-5 job and start working for yourself? Have you dreamt of becoming a blogger and earn by...
I am sure we have a lot of engineers here from Hyderabad. This question is for the students, which is your dream company in Hyderabad and why? This question is...