Hello, I am a beginner in C and am trying to learn very basic sockets and socket programming. Since I am C beginner, dynamic memory, memory management and pointers are all very new to me-and in particular cannot resolve a bad bug in my code, I have been working on it for a while, and thought I would ask here. I would appreciate any help or thoughts about the following code/errors, as it may be very obvious to you.
Code below-which sets up a socket, client and is attempting to read in buffered input from client and print to stdout. I believe I may have a fundamental misunderstanding about memory or pointers:
buggy function:
Code:
//search buffer for \r\n, copy complete message into newly-allocated NULL terminated string. Remove message from buffer by moving remaining content to the front of buffer. inbuffer refers to valid searchable characters in buffer (not junk).
//find_nn loops through first inbuf elements and searches for \r\n. If found returns index of first \r+2, otherwise -1 means no \r\n is found.
int get_msg(char** s, char* buffer, int* inbuffer){
int n = find_nn(buffer, *inbuf);
if(n==-1){
return -1;
}
char* new_s = malloc(sizeof(char)*30); //max size of buffer
if(new_s==NULL){
return -1;
}
memcpy(new_s, buffer, n);
new_s[newline-2]='\0';
*s=new_s;
*inbuffer-=n;
memmove(buffer, buffer+n; inbuffer);
return 0;
}
relevant driver code:
Code:
//reads from a connected client until receives a full message containing a \r\n.
//client is a standard client struct
char *m;
while(!get_msg(&m, clients->buffer, &(clients->inbuf))){
printf("Message: %s\n", m);
free(m);
}
//exit if client closes
It compiles, but the following errors when I try to run the server/client (client writes broken messages to server, which I am aiming to reassemble using \r\n).
ERROR:
==2193==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60400000003c at pc 0x7fd9b1c04deb bp 0x7ffe1b2e9620 sp 0x7ffe1b2e8dc8
READ of size 36 at 0x60400000003c thread T0
#0 0x7fd9b1c04dea in __interceptor_memmove (/usr/lib/x86_64-linux-gnu/libasan.so.4+0x7adea)
#1 0x560117f75e62 in get_msg:142
Further, it seems that the first iteration of my loop works as expected, but i seem to overflow when trying to shift or change my buffer. I appreciate any suggestions you may have.