problem in allocating memory in linux
i signed with stars the 2 rows that are creating the problem.
the first row allocates memory for logfile, that will be used in the second signed row. at the second signed row there is a problem of segmentation fault. This is caused by the fact that "logfile" is not allocated. I'm am sure of this because if i allocate the memory in load() it works. However I want to allocate the memory in the constructor of the class and not in the method load().
I cannot understand why it does not work! This is my first time on linux and so maybe i'm doing something wrong!
Thank you, Marco
server::server(){
port = 0;
serverup = 0;
loaded = 0;
logfile = (char *) malloc(SERVER_PATHS_SIZE*sizeof(char)); //****************************
}
int server::load(int in_id, char *in_name, char *in_ip, int in_port,
char *in_rcon, char *in_logfile){
int err;
sprintf(name, "%s\x00", in_name);
sprintf(ip, "%s\x00", in_ip);
port = in_port;
sprintf(rcon, "%s\x00", in_rcon);
sprintf(logfile,"%s\x00", in_logfile); //**********************************
er开发者_运维技巧r = urt.set(ip, port, rcon);
if(err < 1){
printf("server::load(): error from urt.set()\n");
return 0;
}
printf("server::load(): server %d loaded!\n", id);
loaded = 1;
return 1;
}
I think you are trying to nullterminate in_logfile
and in_rcon
This won't work with printf because printf requires null-terminated string as arguments to %s in the first place.
charptr[known_length] = 0
instead
This is definitely not an answer, but developping in C++ will help you to avoid the memory problems you get with your C-with-classes code.
Use std::strings, then copying them will be trivial (compared to sprintf), and it will be way more safe. Using the deprecated char* makes things way to confusing.
A nice side effect is that you won't need to do manual allocation of the memory (with malloc or new), and eliminating any risk of memory leak.
I don't see the destructor of the server class. Do you have a destructor that frees the memory?
I don't see the code which creates and uses the server object. Could it be that you create the server object but then make a copy of it, and the problem occurs because you do not properly implement copying semantics?
精彩评论