推出ForjaCero平台,帮助系统软件工程岗位招聘与求职
来源标题:Built ForjaCero, a platform to help for system software engineering roles
ForjaCero平台已发布,面向系统软件工程岗位提供支持。该平台旨在帮助相关岗位的匹配与工程实践,具体功能与上线时间原文未详细说明。
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
Two foundational C topics, built up layer by layer - the mental models, how they sit in memory, the dynamic-allocation rules interviewers love, and the patterns (and bugs) that come up again and again.
Every variable lives somewhere in memory. Memory is a long street of numbered houses - each house is a byte, and its number is an address. A pointer is just a variable that stores an address.
int x = 42; // x lives at some address, say 0x100, and holds 42\nint *p = &x; // p holds the value 0x100 (the address of x)
\nThree operators to internalize:
#include <stdio.h>\n\nint main() {\n int x = 42;\n int *p = &x;\n\n printf("Value of x: %d\n", x); // 42\n printf("Address of x: %p\n", &x); // 0x...\n printf("Value of p: %p\n", p); // same address\n printf("Dereferenced p: %d\n", *p); // 42\n\n *p = 100; // change x through the pointer\n printf("x is now: %d\n", x); // 100\n}
\nMental model: p is a signpost. &x writes an address on the signpost. *p says "follow the signpost and look at what is there."
A pointer\u2019s type tells the compiler how many bytes to read when dereferencing. The pointer itself is always the same size (8 bytes on a 64-bit system).
char *cp; // dereference reads 1 byte\nint *ip; // dereference reads 4 bytes\ndouble *dp; // dereference reads 8 bytes
\nExercises - Level 1 (Beginner)
Write swap(int *a, int *b) that swaps two integers. Test it in main.
Write increment(int *n) that adds 1 to a number. Print before and after.
Declare an int, a pointer to it, and a pointer to that pointer (double pointer). Print the value using **.
\nShow solutions\n// 1\nvoid swap(int *a, int *b) {\n int temp = *a;\n *a = *b;\n *b = temp;\n}\n\n// 2\nvoid increment(int *n) { (*n)++; }\n\n// 3\nint x = 5;\nint *p = &x;\nint **pp = &p;\nprintf("%d\n", **pp); // 5
\n\n1.4 - Pointers and arrays
\nIn C, the array name decays to a pointer to its first element.
int arr[5] = {10, 20, 30, 40, 50};\nint *p = arr; // same as &arr[0]\n\nprintf("%d\n", arr[2]); // 30\nprintf("%d\n", *(p + 2)); // 30 -- pointer arithmetic\nprintf("%d\n", p[2]); // 30 -- same thing
\nPointer arithmetic moves by the size of the type: p + 1 on an int* moves 4 bytes; on a double* it moves 8.
// Iterating an array with a pointer\nfor (int *p = arr; p < arr + 5; p++) {\n printf("%d ", *p);\n}
\n1.5 - Pointers and functions
\n// Value is copied -- original unchanged\nvoid fail(int x) { x = 99; }\n\n// Pointer -- we modify the original\nvoid succeed(int *x) { x = 99; }\n\n// Returning a pointer to the caller's variable -- OK\nint safe(int *x) { (x)++; return x; }\n\n// DANGER -- never do this:\nint dangerous() {\n int local = 5;\n return &local; // local is destroyed when the function returns!\n}
\n1.6 - Dynamic memory: malloc, calloc, realloc, free
\nThe stack is automatic but limited. The heap lets you allocate at runtime.
#include <stdlib.h>\n\n// malloc -- raw bytes, uninitialized\nint p = malloc(sizeof(int));\np = 42;\nfree(p);\n\n// calloc -- allocates and zeroes\nint *arr = calloc(10, sizeof(int)); // 10 ints, all zero\nfree(arr);\n\n// realloc -- resize an allocation\nint *buf = malloc(5 * sizeof(int));\nbuf = realloc(buf, 10 * sizeof(int)); // grow to 10 ints\nfree(buf);
\nThe golden rules:
int *safe_alloc(int n) {\n int *p = malloc(n * sizeof(int));\n if (p == NULL) {\n fprintf(stderr, "Allocation failed!\n");\n exit(1);\n }\n return p;\n}
\nExercises - Level 2 (Intermediate)
int* create_array(int n) - allocate an array of n ints, fill with 1..n, return it. Print and free in main.
reverse(int *arr, int n) - reverse in place using pointer arithmetic (no []).
char* my_strdup(const char *s) - allocate, copy the string, return it.
\nShow solutions\n// 1\nint* create_array(int n) {\n int *arr = malloc(n * sizeof(int));\n if (!arr) exit(1);\n for (int i = 0; i < n; i++) arr[i] = i + 1;\n return arr;\n}\n\n// 2\nvoid reverse(int *arr, int n) {\n int *left = arr, *right = arr + n - 1;\n while (left < right) {\n int temp = *left;\n *left++ = *right;\n right-- = temp;\n }\n}\n\n// 3\nchar my_strdup(const char *s) {\n int len = 0;\n while (s[len]) len++;\n char *copy = malloc(len + 1);\n if (!copy) exit(1);\n for (int i = 0; i <= len; i++) copy[i] = s[i];\n return copy;\n}
\n\n1.7 - Function pointers
\nFunctions live in memory too. You can point to them, store them, and pass them.
// Syntax: returntype (*name)(param_types)\nint add(int a, int b) { return a + b; }\nint mul(int a, int b) { return a * b; }\n\nint main() {\n int (*op)(int, int); // pointer to a function (2 ints -> int)\n op = add; printf("%d\n", op(3, 4)); // 7\n op = mul; printf("%d\n", op(3, 4)); // 12\n}
\nThe practical use is callbacks - this is exactly how qsort works:
void apply(int *arr, int n, int (*fn)(int)) {\n for (int i = 0; i < n; i++)\n arr[i] = fn(arr[i]);\n}\n\nint square(int x) { return x * x; }\nint negate(int x) { return -x; }\n// apply(arr, 5, square);
\n1.8 - The void* pointer
\nvoid* can hold any address but can\u2019t be dereferenced without casting. It\u2019s how C writes generic code.
void print_bytes(void *ptr, int n) {\n unsigned char *p = (unsigned char *)ptr;\n for (int i = 0; i < n; i++)\n printf("%02X ", p[i]);\n printf("\n");\n}\n\nint x = 0xDEADBEEF;\nprint_bytes(&x, sizeof(x));
\nPart 2 \u00b7 Structs
\n2.1 - What is a struct?
\nA struct groups related variables under one name - a custom type.
struct Point {\n int x;\n int y;\n};\n\nint main() {\n struct Point p; // declare\n p.x = 10; // dot operator\n p.y = 20;\n struct Point q = {5, 15}; // initialize\n printf("(%d, %d)\n", p.x, p.y);\n}
\ntypedef avoids writing struct every time:
typedef struct {\n int x;\n int y;\n} Point;\n\nPoint p = {10, 20}; // cleaner
\n2.2 - Structs in memory (padding)
\nMembers are laid out in order, but the compiler inserts padding for alignment.
typedef struct {\n char a; // 1 byte\n // 3 bytes padding\n int b; // 4 bytes\n char c; // 1 byte\n // 7 bytes padding\n double d; // 8 bytes\n} Padded; // likely 24 bytes, not 14\n\nprintf("%zu\n", sizeof(Padded)); // probably 24
\nOrder members largest-to-smallest to minimize padding.
Point p = {10, 20};\nPoint *ptr = &p;\n\nprintf("%d\n", (*ptr).x); // dereference then dot\nprintf("%d\n", ptr->x); // arrow operator (preferred)\n\nptr->x = 99; // modify through the pointer
\n2.4 - Passing structs to functions
\ntypedef struct { float x, y, z; } Vec3;\n\n// BAD for large structs -- copies the whole thing\nfloat length_copy(Vec3 v) {\n return sqrt(v.xv.x + v.yv.y + v.zv.z);\n}\n\n// BETTER -- pass by pointer (no copy)\nfloat length_ptr(const Vec3 v) {\n return sqrt(v->xv->x + v->yv->y + v->z*v->z);\n}\n\n// Returning a small struct is fine\nVec3 add(const Vec3 *a, const Vec3 *b) {\n return (Vec3){a->x + b->x, a->y + b->y, a->z + b->z};\n}
\nUse const Vec3 * when you won\u2019t modify - it documents intent and prevents bugs.
// 1\ntypedef struct { float width, height; } Rectangle;\nfloat area(const Rectangle *r) { return r->width * r->height; }\nfloat perimeter(const Rectangle r) { return 2 * (r->width + r->height); }\n\n// 2\ntypedef struct { char name[50]; float grade; int id; } Student;\nStudent top_student(Student *arr, int n) {\n Student *top = &arr[0];\n for (int i = 1; i < n; i++)\n if (arr[i].grade > top->grade) top = &arr[i];\n return top;\n}\n\n// 3\nint cmp_grade(const void *a, const void *b) {\n const Student *sa = a, *sb = b;\n return (sa->grade < sb->grade) - (sa->grade > sb->grade); // descending\n}\n// qsort(students, 5, sizeof(Student), cmp_grade);
\n\nPart 3 \u00b7 Combining structs & pointers
\n3.1 - Linked lists
\nThe classic structure that needs both - a self-referential struct.
typedef struct Node {\n int data;\n struct Node next; // pointer to the same type\n} Node;\n\nNode new_node(int val) {\n Node n = malloc(sizeof(Node));\n n->data = val;\n n->next = NULL;\n return n;\n}\n\nNode prepend(Node *head, int val) {\n Node *n = new_node(val);\n n->next = head;\n return n;\n}\n\nvoid print_list(Node *head) {\n while (head) { printf("%d -> ", head->data); head = head->next; }\n printf("NULL\n");\n}\n\nvoid free_list(Node *head) {\n while (head) { Node *t = head; head = head->next; free(t); }\n}
\n3.2 - Pointer-to-pointer for list modification
\nUsing Node** lets a function modify the head pointer itself - and removes the special case for deleting the first node.
void append(Node **head, int val) {\n Node *n = new_node(val);\n if (!*head) { *head = n; return; }\n Node *curr = *head;\n while (curr->next) curr = curr->next;\n curr->next = n;\n}\n\nvoid delete_val(Node **head, int val) {\n Node **curr = head;\n while (*curr) {\n if ((*curr)->data == val) {\n Node *tmp = *curr;\n *curr = (*curr)->next;\n free(tmp);\n return;\n }\n curr = &(*curr)->next;\n }\n}
\n3.3 - Nested & complex structures
\ntypedef struct { char street[100]; char city[50]; int zip; } Address;\n\ntypedef struct {\n char name[50];\n int age;\n Address addr; // embedded struct\n Address *work_addr; // pointer to struct\n} Person;\n\nPerson p = {\n .name = "Alice",\n .age = 30,\n .addr = {"123 Main St", "Springfield", 12345}\n};\n\nprintf("%s\n", p.addr.city);\nprintf("%s\n", p.work_addr->city); // if allocated
\n3.4 - Opaque pointers & encapsulation
\nHide implementation details, like C++ private members:
// stack.h\ntypedef struct Stack Stack; // incomplete type -- internals hidden\nStack* stack_create();\nvoid stack_push(Stack *s, int val);\nint stack_pop(Stack *s);\nvoid stack_destroy(Stack *s);\n\n// stack.c -- full definition only here\nstruct Stack { int data; int top; int capacity; };\n\nStack stack_create() {\n Stack *s = malloc(sizeof(Stack));\n s->data = malloc(16 * sizeof(int));\n s->top = 0; s->capacity = 16;\n return s;\n}\n\nvoid stack_push(Stack *s, int val) {\n if (s->top == s->capacity) {\n s->capacity *= 2;\n s->data = realloc(s->data, s->capacity * sizeof(int));\n }\n s->data[s->top++] = val;\n}
\nExercises - Level 4 (Advanced)
Doubly linked list with data, prev, next - append, prepend, delete, print_forward/backward.
Generic dynamic array using void*: vec_init, vec_push, vec_get, vec_free.
Binary search tree with insert, search, and inorder traversal.
\n3.5 - Common pointer bugs
\nBugDescriptionDetectionNull dereference*p when p == NULLAlways check the malloc returnDangling pointerAccessing freed memorySet p = NULL after freeBuffer overflowWriting past array boundsvalgrind, AddressSanitizerMemory leakmalloc without freevalgrind --leak-check=fullDouble freefree(p) twiceSet p = NULL after freeStack overflowToo-deep recursionWatch recursion depth\nCompile with maximum safety:
gcc -Wall -Wextra -fsanitize=address,undefined -g program.c
\nPart 4 \u00b7 Expert
\n4.1 - Casting, aliasing & type punning
\n// Inspect the bytes of any value\nfloat f = 3.14f;\nunsigned char bytes = (unsigned char)&f;\nfor (int i = 0; i < sizeof(f); i++)\n printf("%02X ", bytes[i]);\n\n// Safe type punning via a union (avoid strict-aliasing UB)\ntypedef union { float f; uint32_t u; } FloatBits;\nFloatBits fb = { .f = 3.14f };\nprintf("%08X\n", fb.u); // raw bits of the float
\n4.2 - Multidimensional & pointer arrays
\n// 2D array -- contiguous in memory\nint matrix[3][4];\nint (*row_ptr)[4] = matrix; // pointer to an array of 4 ints\n\n// Array of pointers -- rows can have different lengths (jagged)\nint *rows[3];\nrows[0] = malloc(2 * sizeof(int));\nrows[1] = malloc(5 * sizeof(int));\nrows[2] = malloc(3 * sizeof(int));
\n4.3 - Const correctness
\nint x = 5;\nconst int *p = &x; // can't change *p, can change p\nint * const q = &x; // can change *q, can't change q\nconst int * const r = &x; // can change neither\n// Read right-to-left: "r is a const pointer to const int"
" }, { id: 'malloc-calloc', title: 'malloc vs calloc', blurb: 'Two ways to grab heap memory: what each does, how they differ in initialization, arguments and speed, with examples and the gotchas interviewers ask about
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。