Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Segmentation Fault in Visual Studio Code while debug C Program

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}

>Solution :

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("%99s", str);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading