Here, I am basically trying to input a string, break it into individual words and assign each word to a char pointer ptr[i]
.On executing the following code, if I input string of more than one word, it shows Segmentation fault (core dumped)
.
I used gdb for debugging. But after I visit while loop 2nd time, it showed
Program received signal SIGSEGV, Segmentation fault.
0x0000003b64a81321 in __strlen_sse2 () from /lib64/libc.so.6
The solution for it is to allocate memory to each ptr[i]
before strcpy(ptr[i],cp);
using ptr[i]=new char[sizeof(cp)];
.
But, how is it that no memory allocation needed for ptr[0]? If I don't allocate memory to ptr[0], are there any chances of something else being overwritten? I am asking it out of curiosity, I know its always better to allocate memory.
Here is the code:
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int main()
{
int i,j;
string s1;
getline(cin,s1);
char s[100],*ptr[10];
strcpy(s,s1.c_str());
char *cp;
cout<<"string is: "<<s1<<endl;
cp=strtok(s," ");
i=0;
while(cp!=NULL)
{ cout<<cp<<endl;
strcpy(ptr[i],cp);
cp=strtok(NULL," ");
i++;
}
for(j=0;j<i;j++)
{ cout<<ptr[j]<<endl;
}
return 0;
}