Reputation: 1301
So I'm working on writing a simple web server in C, and now I'm trying to figure out how to transfer larger files. I'm trying to do it with a file ~40MB right now and I'm getting a segmentation fault (at least that's what wget tells me!)
The thing is, the program itself never actually gives me an error, it just quits out, it's only when I try and get the file using wget that wget says that it errors in a seg fault. Here's the code that sends the file:
while( 1 ) {
int bytes_read = fread( file_buffer, 1, BUFFER_SIZE, f );
printf( "Bytes read: %d\n", i * 1024 );
if ( bytes_read == 0 ) {
if ( logging > 0 ) {
printf( "End of file reached...\n" );
}
break;
} else {
send( client, file_buffer, strlen( file_buffer ), 0 );
if ( logging > 1 ) {
printf( "Buffer (%d): %s\n\n", bytes_read, file_buffer );
}
}
i++;
}
Any ideas what's going wrong? It works fine with smaller files, just not this one. Oh, and the bytes read varies each time I try, it gets anywhere from 240000 to 770000. Thoughts? Thanks!
Upvotes: 2
Views: 1733
Reputation: 6846
fread doesn't null terminate strings. You need to use bytes_read as the length parameter to send, not strlen.
You also either need to null-terminate the string before trying to print it, or provide a length with the %s formatter. For example: printf( "Buffer (%d): %.*s\n\n", bytes_read, bytes_read, file_buffer );
Upvotes: 1
Reputation: 14786
You shouldn't use strlen(file_buffer) to specify how many bytes to send; this will break in many circumstances, and will always break when the file sent is bigger than your buffer. Why not just use bytes_read to specify how many bytes to send?
Upvotes: 1