-4

I want to input two strings at different memory locations but after taking the first input it shows an error "segmentation fault(core dumped"). I am not getting what's wrong with this code.

#include <stdio.h>
#include<iostream>
using namespace std;

int main()
{
    char *str;
    int i;
    scanf("%s",str+0);
    scanf("%s",str+1);
    return 0;
}

But when I only take one input it works fine.

#include <stdio.h>
#include<iostream>
using namespace std;

int main()
{
    char *str;
    int i;
    scanf("%s",str+0);

    return 0;
}

Why?

KyleL
  • 855
  • 6
  • 24
Naresh
  • 155
  • 1
  • 9

1 Answers1

6

Because you do not allocate any memory to str before using it in your scanf().

You need to allocate some memory with malloc()

Both your codes exhibit Undefined Behavior as you try to access unsafe memory.

Arun A S
  • 6,421
  • 4
  • 29
  • 43