Home > database >  why do i get Segmentation fault executing this code?
why do i get Segmentation fault executing this code?

Time:04-06

I'm trying to figure out the issue with this code:

int main(int argc, char *argv[])
{
    char *s;
    scanf("%s\n", s);

    char *t = malloc(sizeof(*s)   1);

    strcpy(t, s);
    t[0] = toupper(t[0]);
    printf("s: %s\n", s);
    printf("t: %s\n", t);

    free(t);
    return 0;
}

I was trying to upper case the first alphabet of my input to get for example hi! changed into Hi!.

CodePudding user response:

  1. You are using scanf on a char* without first allocating memory to it. This may lead to segmentation fault. In fact, the following code :

    #include<stdio.h>
    int main()
    {
        char* str;
        scanf("%s", str);
        printf("%s\n", str);
        return 0;
    }
    

    does give segmentation fault sometimes. Instead you can use a char array instead of a char* if you want to avoid malloc before scanf . You can use fgets instead of scanf to prevent writing out of bounds or you can check with scanf itself like this:

    char s[100];
    if(scanf("           
  • Related