( 返回 2017年暑期系統軟體課程:台北場次 )
我們期望學員在參加系統軟體課程之前,能夠充分回答以下提問,不僅理解自身學習背景,也藉此和其他學員交流。 – jserv
uint16_t
的版本。在什麼場合會用到下方的程式碼?#include <stdint.h>
uint32_t func(uint32_t x) {
uint32_t n = x;
n = ((n & 0xffff0000) >> 16) | ((n & 0x0000ffff) << 16);
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
return n;
}
uint32_t half_add(uint32_t a, uint32_t b) {
if (b == 0) return a;
uint32_t sum = a ^ b; /* 相加但不進位 */
uint32_t carry = (a & b) << 1; /* 進位但不相加 */
return half_add(sum, carry);
}
char *p;
...
*p = (*p) & ~1;
malloc
程式碼使其正確運作,並提供對應的 free
實作。#include <stddef.h>
#include <unistd.h>
#include <pthread.h>
struct header_t {
size_t size;
unsigned is_free;
struct header_t *next;
} *head, *tail;
static struct header_t *
get_free_block(size_t size) {
struct header_t *curr = head;
while (curr) {
if (curr->is_free && curr->size >= size) return curr;
curr = curr->next;
}
return NULL;
}
pthread_mutex_t global_malloc_lock;
void *malloc(size_t size) {
size_t total_size;
void *block;
struct header_t *header;
if (!size) return NULL;
if ((header = get_free_block(size)) {
header->is_free = 0;
return ? /* FIXME */
}
total_size = sizeof(struct header_t) + size;
if ((block = sbrk(total_size)) == (void *) -1)
return NULL;
header = block;
header->size = size;
header->is_free = 0;
header->next = NULL;
... /* FIXME */
return ? /* FIXME */
}
fork.c
,在 GNU/Linux 上編譯得到名為 fork
的執行檔,我們可用 ./fork | wc -c
計算輸出的 -
字元,請解釋程式行為和輸出的 -
字元數量的關聯。#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
for (int i = 0; i < 3; i++) {
fork();
printf("-");
}
wait(NULL); wait(NULL); wait(NULL);
return 0;
}