#include <stdio.h>
int main()
{
// 將整型 (int) -1,即 ffffffff,轉型成 size_t,進而得到 size_t 的最大值。
// (~(size_t)0)
size_t length = (size_t)-1;
printf("max value of size_t: %zu\n", length);
printf("sizeof(size_t): %lu\n", sizeof(size_t));
}
// $ cat /proc/`pidof mmap`/maps
// 00000000-100000000 rwxp 00000000 00:00 0
// 100000000-100001000 r-xp 00000000 00:0f 24080529 /nfs_home/chenwj/tmp/mmap
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
// 4 * 1024 * 1024 * 1024 的寫法,會因為 4 預設型別為 int 而導致 overflow。
#define DEFAULT_CODE_GEN_BUFFER_SIZE (4UL << 30)
int main()
{
void *ptr;
size_t code_gen_buffer_size = DEFAULT_CODE_GEN_BUFFER_SIZE;
int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED;
// gcc -Wl,-Ttext-segment=0x100000000 -fPIE -pie hello.c -o hello
// mmap 映射虛擬位址 4G 以下所有空間。
ptr = mmap(0, code_gen_buffer_size,
PROT_WRITE | PROT_READ | PROT_EXEC,
flags, -1, 0);
if (ptr == MAP_FAILED)
{
printf("mmap failed!\n");
abort();
}
printf("ptr: 0x%016lx\n", (unsigned long)ptr);
sleep(100);
}
有關C語言的struct進階初始化typedef struct _stu {
char name[12];
int id;
} stu;
stu jenny;
strutc _stu zakk;
-
Using boolean values in Ctypedef enum { false, true } bool;
int main()
{
const bool char_is_signed = (char)-1 < 0;
if (char_is_signed)
{
printf("signed char\n");
}
else
{
printf("unsigned char\n");
}
}
-
fscanf 讀取字串以空白為界,欲達到讀取一行的字串。
#include <stdio.h>
FILE *my_file_ptr = fopen("some/path/file.txt", "r");
if (my_file_ptr != NULL) {
char line[300];
// Read anything that is not line end, until line end is encountered.
while (fscanf(my_file_ptr, "%[^\n]\n",line) != EOF) {
printf("%s", line);
}
}
-
透過 shift 和 mask 達成。
unsigned char bytes[4];
unsigned long n = 175;
bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;