-3

have been learning about pointers and arrays lately. If I'm not wrong we can implement both char arrays and char pointers to store string type data. But here in the below example when we initialize a string to char array it works, but when we applycin>>subStr it gives the error. The following code in C++ gives me SEGMENTATION FAULT (core dumped) Error Message.. The main issue is with applying the input through cin>> I would like to know more about why this happens.

#include<iostream>
using namespace std;

int main(){
    char myStr[] = "We are learners";
    char *subStr;
    cout<<"Enter the substring : ";
    cin>>subStr;
    cout<<"You entered " <<subStr;
    return 0;
}
The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49
Jyotirmoy
  • 45
  • 1
  • 11
  • 7
    `subStr` is an uninitialized pointer. Were do you think it's pointing to? Were do you think will `cin>>subStr` write the input? – Lukas-T Sep 15 '22 at 14:52
  • This sample doesn't even compile to me. How are you supposed to write into a pointer value from std input? – The Dreams Wind Sep 15 '22 at 14:52
  • 1
    1) forget that C-style arrays exist in the language. 2) always use `std::string`, `std::array` or `std::vector`. 3) Please read [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). 4) Be aware of [UB](https://en.cppreference.com/w/cpp/language/ub). Btw; a segmentation fault is about as easy a problem as you can get when investigating with your debugger - you'll likely get a nice stack trace and all your local variables to inspect - easy street. – Jesper Juhl Sep 15 '22 at 15:13
  • You are wrong about pointers. The only thing you can store in a pointer variable is a pointer. You **can** store chars in the memory that pointer points to, but that's different thing, and the reason your code crashes. If you don't know what an uninitilaised pointer is then you need to go back to the books you are learning from. – john Sep 15 '22 at 15:21

1 Answers1

2

The problem

Your subStr pointer is just that: a pointer. It doesn't actually point to any memory, so what is the program supposed to read into? This is why you get a segmentation fault.

A "solution"

You could specify subStr as an array, and this would work sometimes.

#include <iostream>

using namespace std;

int main() {
    char subStr[16];

    cout << "Enter the substring : ";
    cin >> subStr;

    cout << "You entered " << subStr;

    return 0;
}

Now subStr does actually represent memory, but only 15 characters (and a null terminator) worth. If the input is less than this length, the program works.

But if it's longer, the program overflows the memory you've provided, almost certainly causing problems.

The right path

Learning about arrays is good, but just use std::string when at all possible to avoid these issues.

Chris
  • 26,361
  • 5
  • 21
  • 42