---
# System prepended metadata

title: Linux Kernel開發學習日誌2020.2.25
tags: [C, K&R]

---

# Linux Kernel開發學習日誌2020.2.25
###### tags: `C` `K&R` 


# 行動筆記

* 分析 lab0 需要什麼
    * typedef研究
    * malloc研究 明天學 Dynamic memory allocation (Stack & Heap)
    * function pointer (K&R 遇到的問題)

------------------
# 構思筆記

## Dynamic memory allocation (Stack & Heap)
[geekforgeeks](https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/)
The following declares a variable i on the stack:
```c
int i;
```
When I ask for an address using ```&i``` I get the actual location on the ==stack==.

When I allocate something dynamically using ```malloc```, there are actually **TWO** pieces of data being stored.

* The dynamic memory is allocated on the heap, and
* the pointer itself is allocated on the stack.
 
So in this code:
```c
int* j = malloc(sizeof(int));
```
This is allocating space on the heap for an integer. It's also allocating space on the stack for a pointer ```j```. 
The variable ```j```'s value is set to the address returned by ```malloc```.




-----------
# 封存筆記:

## Why should we typedef a struct so often in C?

>[Stackoverflow question: 252780](https://stackoverflow.com/questions/252780/why-should-we-typedef-a-struct-so-often-in-c)

As Greg Hewgill said, the typedef means you no longer have to write struct all over the place.
That not only save keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.

Code:

```c
typedef struct {
    int x, y;
}Point;

/*
 * point_new:
 * @ x, y: 2 integer
 * @ a: a structure which type is Point 
 *     (which is an alias of structure.)
 */

Point point_new(int x, int y) // function 括號要單獨一行
{
    Point a;
    a.x = x;
    a.y = y;
    return a;
}
```

--------



## The difference between Stack and Heap

[video](https://www.youtube.com/watch?v=PdvGEI-P3-M)


<img src="https://i.imgur.com/1tEiaHQ.jpg" height=400/>

<br><br>

|               | Stack                       | Heap                                           |
|---------------|-----------------------------|------------------------------------------------|
| How to access | Access directly by variable | Access indirectly by pointer & malloc function |
| size          | size-static                 | size-dynamic                                   |

code:

```c
int main() {
    int a,b,c,d,e;
    int *p;
    p = malloc(10);
}
```

