Debug why does size_t not work as a data member?
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)
{开发者_Python百科
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 n
before it's ever initialized (actually, n
never gets initialized).
So the line
while(cstr[n++])
is undefined behavior.
Try:
test(const char *cstr) : n(0) // <-- initialize n
{
size_t j=0;
while(cstr[n++])
;
//j = n;
}
In the first case, you're using uninitialized n
which is why your program crashes which is one of the possibilities of undefined behaviour (UB). Using uninitialized variables invokes UB.
test(const char *cstr)
{
size_t j=0; //<--- here you want to do : n = 0;
while(cstr[n++])
;
//j = n;
}
Or better yet, you should use member-initialization-list as:
test(const char *cstr) : n(0)
{ //^^^^^^ it is member-initialization-list
while(cstr[n++]) ;
}
Make sure cstr
is null-terminated string, otherwise your code would still have UB.
The private member size_t n in the first example is never initialized. Its value is undefined. Add n=0 before your while loop and it should work the same.
精彩评论