Home > Back-end >  Segmentation Fault in Visual Studio Code while debug C Program
Segmentation Fault in Visual Studio Code while debug C Program

Time:11-11

I'm learning C. When I use this code on Linux I didn't get this kind of error. Can you show me how to fix it? I've tried many solutions but nothing worked T_T. Thanks in advance.

segmentation error

code

error2

Here's the code

#include <conio.h>
#include <stdio.h>

void main()
{
    int a;
    float x;
    char ch;
    char* str;

    printf("Enter integer number: ");
    scanf("%d", &a);
    printf("\nEnter real number : ");
    scanf("%f", &x);
    printf("\nEnter a character: ");
    fflush(stdin); 
    scanf("%c", &ch);
    printf("\nEnter a string: ");
    fflush(stdin);
    scanf("%s", str);

    printf("\nData:");
    printf("\n Integer: %d", a);
    printf("\n Real: %.2f", x);
    printf("\n Character: %c", ch);
    printf("\n String: %s\n", str);
}

CodePudding user response:

For starters this call

fflush(stdin);

has undefined behavior. Remove it.

Secondly in this call of scanf

scanf("%c", &ch);

you should prepend the conversion specifier with a space

scanf(" %c", &ch);
      ^^^^^

Otherwise white space characters as the new line character '\n' will be read.

The pointer str is not initialized and has an indeterminate value

char* str;

So this call

scanf("%s", str);

invokes undefined behavior.

You should declare a character array as for example

char str[100];

and call the function scanf like

scanf("           
  • Related