1. char *name = malloc(20);
name = "abcdef";
這兩條語句合起來會導致內存泄露,因為name先指向堆(heap),后又指向了常量區。
2.共用體所有的成員共用一段內存:
union data{
short int i;
char ch;
}share;
int a = share.ch;表示用(char)的格式解釋共用體所占的空間。a.任何時刻只有一個變量。b.不能在定義的時候賦值。c.同類型的共用體變量是可以整體賦值的。d.共用體變量起作用的是最后一次存放的成員。
example:
[root@localhost test]# gcc 12_13_2.c
[root@localhost test]# ./a.out
65
[root@localhost test]# cat 12_13_2.c
#include <stdio.h>
union data
{
short int i;
char ch;
}share;
int main()
{
int a;
share.i = 65+256;
a = share.ch; //表示用(char)的格式解釋共用體所占的空間
printf("%d\n",a); //結果是65
}
3.malloc()分配后不初始化數據,calloc()分配后數據初始化為零。realloc()分配后所返回的指針不一定是原來的那個指針。
4.結構體的對齊特性:
結構體內的元素具有對齊特性(一般是4字節對齊),結構體本身也有對齊特性(與其所占內存最大的那個元素的大小對齊)。而且整個結構體的長度必須是齊對齊特性的倍數。
兩個同類型的結構體可以整體賦值,如
struct AnyOne a, b;
a = b; //這是可以的
5.NULL在C和C++中的定義:
#undef NULL
#if defined(__cplusplus)
#define NULL 0
#else
#define NULL ((void *)0)
#endif
6.查看堆(heap)的分配和釋放:
[root@localhost test]# valgrind --tool=memcheck --leak-check=full ./a.out
7.umask的作用:將對應的位取反,若umask=022,則將組和其他用戶的w權限清零。
8.判斷一個變量是不是無符號數:
#define IS_UNSIGNED(a) ((a >= 0) ? (~a > 0 ? 1 : 0) : 0)
9.
[root@localhost test]# cat 12_13_4.c
#include <stdio.h>
#include <string.h>
void func(char str[50])
{
printf("%d, %d\n", sizeof(str), strlen(str));
}
int main()
{
char s[50] = "abcdefght";
func(s);
}
[root@localhost test]# gcc 12_13_4.c
[root@localhost test]# ./a.out
4, 9
[root@localhost test]#
void func(char str[50])這里的50沒有任何意義。sizeof(str)這里str代表數組首元素的地址。
10.
[root@localhost test]# cat 12_13_5.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char stra[] = "HelloWorld";
char *strb = stra;
printf("%d, %d\n", sizeof(stra), sizeof(strb++)); //stra代表整個數組,11是因為要算上'\0'
printf("%d, %d\n", strlen(strb), strlen(strb++)); //參數從右到左計算
//sizeof()是個關鍵字,在預編譯時已經計算出了大小,不做運算
}
[root@localhost test]# gcc 12_13_5.c
[root@localhost test]# ./a.out
11, 4
9, 10
[root@localhost test]#
11.
函數指針:
例如,
int func(int x); /* 聲明一個函數 */
int (*f) (int x); /* 聲明一個函數指針 */
f=func; /* 將func函數的首地址賦給指針f */
賦值時函數func不帶括號,也不帶參數,由於func代表函數的首地址,因此經過賦值以后,指針f就指向函數func(x)的代碼的首地址。
指針函數:
類型標識符 *函數名(參數表)
例如,
int *f(x,y);
12.kill -l :列出所有信號
13.注意將while(1)和sleep()(睡眠)區別開來。
14.信號處理程序不可重入函數:
a.函數返回值是指針,傳遞給函數的參數有指針。
b.內部有malloc()或free()調用的函數。
c.使用了全局數據結構的函數。
d.實現時用了標准I/O函數。
15.alarm定時產生的誤差是比較大的。settimer可以用來精確定時。