我希望實現一個Web套接字握手,並使用下面的代碼片段。 但我開始釋放我動態分配的內存時出現分段錯誤。第一次使用免費功能的地方出現錯誤。請幫忙。釋放內存時出現分段錯誤
char rbuf[656];
char handshake[800];
char *handshake_part2, *handshake_part3,*key,*magic,*final;
unsigned char hash [20];
key=strndup(rbuf+359, 24);
magic = malloc(strlen("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")+2);
strcpy(magic,"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
final = malloc (60);
final = strcat(key,magic);
SHA1(final,strlen(final),hash);
base64(hash, sizeof(hash));
handshake_part2= malloc(400);
handshake_part2= base64(hash, sizeof(hash));
strcpy (handshake,"HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: Websocket\r \nConnection: Upgrade\r\nSec-WebSocket-Accept: ");
strcat(handshake,handshake_part2);
handshake_part3= malloc(400);
handshake_part3="\r\nWebSocket-Origin: http://localhost:9605\r\nWebSocket-Location: ws://localhost:9609/\r\n\r\n";
strcat(handshake,handshake_part3);
printf("Response Header :\n%s", handshake);
free(handshake_part3);
handshake_part3=NULL;
printf("Free 1");
free(handshake_part2);
handshake_part2=NULL;
printf("Free 2");
free(final);`
final=NULL;
printf("Free 3");
free(magic);
magic=NULL;
printf("Free 4");
free(key);
請修復縮進。 – sean 2012-07-16 21:02:28
您需要通過檢查malloc調用後的handshake_part3的值來檢查內存是否在第一位分配: – Raj 2012-07-16 21:03:06
爲什麼'malloc'在第一位? – netcoder 2012-07-16 21:17:50