-7
#include< iostream >
#include< sstream >
#include< string.h >
using namespace std;
int main()
{
    string s = "hello this is vit university i love chocolates";
    istringstream iss(s);
    string temp;
    char* coll;
    int i = 0;
    while (iss >> temp)
    {
        cout << temp << endl;//(char *)temp.c_str();
        strcpy(coll, "something here");
        //i++;
        //cout<<(char *)temp.c_str()<<endl;
    }
    return 0;
}

Error in code, strcpy(coll,"sldjs"); is exiting the code, what is the issue here?

  • 1
    For starters, `strcpy` assumes you have usable memory. – chris Mar 05 '14 at 17:29
  • 2
    You should edit your title so it reflects your specific question. – A.E. Drew Mar 05 '14 at 17:30
  • 4
    `coll` is an uninitialized pointer. `strcpy` writes characters to its first argument. Writing to an uninitialized pointer is undefined behavior. You need to allocate space using `new` or a stack array (`char coll[32]`); you can search for more information on both of these. – TypeIA Mar 05 '14 at 17:31
  • Can you please tell us what you're trying to solve? – stefan Mar 05 '14 at 17:32

2 Answers2

1
char* coll;

That's an uninitialised pointer, which doesn't point to valid memory.

strcpy(coll,"something here");

That copies the string through the pointer, giving undefined behaviour; typically, either a protection fault, or random memory corruption.

If you really want to mess around with the C library, then you'll need a buffer to write into:

char coll[SOME_SIZE_YOU_HOPE_IS_BIG_ENOUGH];

or you could stick with the C++ library, which will manage the memory for you:

std::string coll;
coll = "something here";
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

You need to allocate memory where you are going to copy your "something here". Change this code snippet

char* coll;
int i = 0;
while (iss >> temp)
{
    cout << temp << endl;//(char *)temp.c_str();
    strcpy(coll, "something here");
    //i++;
    //cout<<(char *)temp.c_str()<<endl;
}

to

int i = 0;
while (iss >> temp)
{
    cout << temp << endl;//(char *)temp.c_str();
    char* coll = new char[strlen( "something here" ) + 1];
    strcpy(coll, "something here");
    //i++;
    //cout<<(char *)temp.c_str()<<endl;
    delete []coll;
}

Also take into account that correctly specified headers are

#include< iostream >
#include< sstream >
#include< string >
#include< cstring >
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335