我正在尝试使用此代码从套接字读取完整的消息:
int readWholeMessage(char* &message){
bool ended=false;
bool first=true;
int mlen=0;
int len = BUFFLEN;
char* buffer;
char* sol=new char[BUFFLEN];
while(!ended) {
buffer = new char[BUFFLEN];
n = (int) read(s, buffer, (size_t) BUFFLEN);
if (n < 0) {
perror("ERROR reading from socket");
close(s);
return 1;
}
else{
//looks for the end of the message: "\r\n"
for(int i=0; i<BUFFLEN-1; i++){
mlen++;
if(buffer[i]=='\r' && buffer[i+1]=='\n'){
ended=true;
break;
}
}
mlen++;
//saves the result in sol and deletes buffer
if(first){
strcpy(sol, buffer);
first=false;
}
//creates a new bigger array, saves the whole message,
//deletes de old array points the pointer sol to the new one
else {
len+=BUFFLEN;
char *bufferAux = new char[len+1];
strcpy(bufferAux, sol);
strcat(bufferAux,buffer);
delete [] sol;
sol=bufferAux;
}
delete [] buffer;
}
}
message = new char[mlen+1];
strncpy(message, sol, (size_t) mlen);
message[mlen]= '\0';
delete[](sol);
return 0;
}
但是SIGSEGV和SIGABRT在delete [] sol中随机出现;并删除[]缓冲区;取决于要阅读的消息的长度。 如果BUFFSIZE为8,则添加1可解决问题,但我需要它为256。 有些帮忙吗?