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

radha gogia

radha gogia

@radha-BTDzli Oct 26, 2024

[HASHTAG]#include[/HASHTAG]<stdlib.h>
[HASHTAG]#include[/HASHTAG]<string.h>
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

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Vishal Sharma

    Vishal Sharma

    @vishal-pysGmK May 30, 2023

    radha gogia[HASHTAG]#include[/HASHTAG]<stdlib.h>
    [HASHTAG]#include[/HASHTAG]<string.h>
    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<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    int main(void)
    {
    char *p = (char *)malloc(1024);
    strcat(p, "abc");
    printf("\n %s \n", p);
    return 0;
    }