Hi, I got a Segmentation Fault(core dump) error when running the following code. Seems like the struct pointer does not work when used as the constructor parameter. I am using ubuntu-12.10-64bit system. Any one has any solution for that? Thanks very much.
I will recommend not using strncpy when copying from one string to another because in the case of source string being longer than destination string, something weird starts to happen with the destination string in that it it copies more than it's specified capacity and reallocates itself. Example, replace this main with the one posted by Bourgond Aries and see the length of the strings after it has run.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main() {
config temp;
// printf("%lu %lu %lu\n", sizeof(temp.code), sizeof(temp.period), sizeof(temp.state));
strncpy(temp.code,"To be or not to be",sizeof(temp.code));
strncpy(temp.period,"To be or not to be",sizeof(temp.period));
strncpy(temp.state,"To be or not to be",sizeof(temp.state));
std::cout<<"Debug 1\n";
star1 item(&temp);
printf("%lu %lu\n", strlen(temp.code), strlen(temp.period));
std::cout<<"Debug 2\n";
return 0;
}
I will recommend not using strncpy when copying from one string to another because in the case of source string being longer than destination string,
That why one uses strncpy as opposed to strcpy. Of course, one needs to make an effort to ensure the resultant string is nul terminated, which the OP isn't doing (but which isn't a problem in his code.)
something weird starts to happen with the destination string in that it it copies more than it's specified capacity and reallocates itself.
arrays of type char do not reallocate themselves.
It's hard to say what is causing the problem the OP has since the code provided obviously isn't the code that is producing the problem as it will not compile for multiple reasons.
There is a typo in the codes. I forgot to put ; after class definition. But in my simulation, I did put ; so there is no compilation error but failed at run time.
There is a typo in the codes. I forgot to put ; after class definition. But in my simulation, I did put ; so there is no compilation error but failed at run time.
That is not the only thing keeping the code you posted from compiling. Please test code to make sure the problem is reproduced by it before posting it if you've simplified or changed it for posting.