Can somebody tell me why the first program crashes, yet the second one doesn’t?
First one (crashes):
#include <cstdlib>
class test
{
public:
test(const char *cstr)
{
size_t j=0;
while(cstr[n++])
;
//n = j;
}
private:
size_t n;
};
int main()
{
test("Hello, world!\n");
return 0;
}
Second one does not crash (use variable local to the constructor rather than data member to count):
#include <cstdlib>
class test
{
public:
test(const char *cstr)
{
size_t j=0;
while(cstr[j++])
;
n = j;
}
private:
size_t n;
};
int main()
{
test("Hello, world!\n");
return 0;
}
Running MinGW on windows.
make: * [run] Error -1073741819
Quite simply because in your first example the constructor uses
nbefore it’s ever initialized (actually,nnever gets initialized).So the line
is undefined behavior.
Try: