Challenge: What does this code do?
Here is a pretty simple C program, running on Linux. Can you tell me what you expect its output to be?#include #include #include #include #include #include #define BUFFER_SIZE (3ULL * 1024 * 1024 * 1024) // 3GB in bytes int main() { int fd; char *buffer; struct stat st; buffer = (char *)malloc(BUFFER_SIZE); if (buffer == NULL) { return 1; } fd = open("large_file.bin", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); if (fd == -1) { return 2; } if (write(fd, buffer, BUFFER_SIZE) == -1) { return 3; } if (fsync(fd) == -1) { return 4; } if (close(fd) == -1) { return 5; } if (stat("large_file.bin", &st) == -1) { return 6; } printf("File size: %.2f GB\n", (double)st.st_size / (1024 * 1024 * 1024)); free(buffer); return 0; }And what happens when I run:head large_file.bin | hexdump -CThis shows both surprising behavior and serves as a good opening for discussion on a whole bunch of issues. In an interview setting, that can give us a lot of insight into the sort of knowledge a candidate has.
Here is a pretty simple C program, running on Linux. Can you tell me what you expect its output to be?
#include
#include
#include
#include
#include
#include
#define BUFFER_SIZE (3ULL * 1024 * 1024 * 1024) // 3GB in bytes
int main() {
int fd;
char *buffer;
struct stat st;
buffer = (char *)malloc(BUFFER_SIZE);
if (buffer == NULL) {
return 1;
}
fd = open("large_file.bin", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd == -1) {
return 2;
}
if (write(fd, buffer, BUFFER_SIZE) == -1) {
return 3;
}
if (fsync(fd) == -1) {
return 4;
}
if (close(fd) == -1) {
return 5;
}
if (stat("large_file.bin", &st) == -1) {
return 6;
}
printf("File size: %.2f GB\n", (double)st.st_size / (1024 * 1024 * 1024));
free(buffer);
return 0;
}
And what happens when I run:
head large_file.bin | hexdump -C
This shows both surprising behavior and serves as a good opening for discussion on a whole bunch of issues. In an interview setting, that can give us a lot of insight into the sort of knowledge a candidate has.
What's Your Reaction?