1

When try running this following program:-

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("HI whats your name? ");
    char name;
    scanf("%s",&name);
    printf("So your name is %s ", name);
    return 0;
}

But when try running my code I get an error telling this

Process terminated with status -1073741819 (0 minute(s), 11 second(s))

I have no idea what this error means. This program is a really simple C program to take the name as input and greet the user. Please tell me how can I fix this error.

theindiandev
  • 43
  • 2
  • 7
  • 1
    `char name;` -> `char name[100];` and `scanf("%s", &name);` -> `scanf("%s",name);` . Read the compiler warnings. Read the chapter dealing with strings in your beginner's C text book. Learn how to use your debugger. Knowing how your debugger works will save you a lot of time in the future – Jabberwocky Oct 14 '20 at 09:11
  • 2
    @Jabberwocky Problems like these are common by people coming from higher level languages with built-in string types. There's a general "what are strings in C" question we can use as duplicate (see dupe target). That one also covers missing null termination FAQs. – Lundin Oct 14 '20 at 09:21

1 Answers1

5
char name;

Reserves just one byte for the name, so when you enter the name it creates a buffer overflow that produce a memory violation error. Use a char array instead:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("HI whats your name? ");
    char name[256];      //Note we are reserving space for up to 255 chars,
                         //because the 256th must be reserved for the ending null.
    scanf("%s",name);    //Note also that we don't use the & because an array is already a pointer
    printf("So your name is %s ", name);
    return 0;
}

A buffer overflow is a process where you try to stuff in a buffer more items than its size can contain. In your case you start to store the name characters in the location of the variable name and continue storing in the following memory cells eventually overwriting the variables that follows it.

Moreover, because the variable name is an automatic variable, it resides on the stack. When you store the input character will overwrite also the return address, that in most systems is saved on the same stack, with the result that when returning from the function the processor jumps to a wrong address.

When opportunely crafted a buffer overflow can voluntarily change the return address to force processor to execute malicius code. The so called "buffer overflow exploit".

Frankie_C
  • 4,764
  • 1
  • 13
  • 30