I have picked up this program from somewhere and am trying to understand it.
This line: s[j++] = s[i];
is the cause of crash. My understanding is that for the first time at least the program should not crash because j will be incremented later on. First time j and i's value will be 0.
So, this will be like s[0] = s[0];
Why should this crash?
#include <iostream>
using namespace std;
void squeeze(char a[], char c);
int main()
{
squeeze("qwiert", 'i');
return 0;
}
void squeeze(char s[], char c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
{
if (s[i] != c)
{
std::cout << "\ni: " << s[i];
s[j++] = s[i];
std::cout << "\nj: " << s[j];
std::cout << "\nj : " << j;
exit(0);
}
}
s[j] = '\0';
}
Output:
i: q
After this the program crashes.
I have put the exit statement to stop the program that point to find the segfault.