Can anyone help me understand what these two lines are doing
buf = (char *)(malloc(2 * pagesize) & pagemask);
buf = (char *)(((long)buf + pagesize) & ∼pagemask);
I understand malloc but not sure what the & operation is trying to achieve in both expressions
Pagesize and pagemask are defined as follows earlier
pagesize = sysconf(_SC_PAGESIZE);
pagemask = pagesize - 1;
Thanks!
Edit1
This code is from a book "Unix FileSystems" by Steve D. Pate
Edit2
This is the full code
#include <sys/unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include “sys/fs/vx_ioctl.h”
#define MB (1024 * 1024)
main(int argc, char argv[])
{
char *buf;
int i, fd, advisory;
long pagesize, pagemask;
if (argc != 2) {
exit(1);
}
if (strcmp(argv[1], “VX_SEQ”) == 0) {
advisory = VX_SEQ;
} else if (strcmp(argv[1], “VX_RANDOM”) == 0) {
advisory = VX_RANDOM;
} else if (strcmp(argv[1], “VX_DIRECT”) == 0) {
advisory = VX_DIRECT;
}
pagesize = sysconf(_SC_PAGESIZE);
pagemask = pagesize - 1;
buf = (char *)(malloc(2 * pagesize) & pagemask);
buf = (char *)(((long)buf + pagesize) & ∼pagemask);
fd = open(“myfile”, O_RDWR);
ioctl(fd, VX_SETCACHE, advisory);
for (i=0 ; i<MB ; i++) {
read(fd, buf, 4096);
}
}
&is a binary and.mallocand immediately do arithmetic on the result. Later you will need to pass the original pointer tofree.mallocmight return. Then write it down on paper. Then perform the second operation using pen and paper. Do that for a few different numbers, and you might begin to see a pattern. Pen and paper are two very important parts of a programmers toolbox, still.