结构体对齐
#include<stdio.h>
struct Test {
int i;
char ch1;
float f;
char ch2;
}__attribute__((packed));
int main(){
struct Test t = {
1, 'c', 2.4, 'r'
};
printf("sizeof t = %ld\n", sizeof(t));
return 0;
}
- attribute((packed))要求编译器不对齐
动态内存分配
-
man malloc 查看手册
SYNOPSIS #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); void *calloc(size_t nmemb, size_t size); void *realloc(void *ptr, size_t size);
-
malloc 申请size的内存空间,返回viod* 指针,指向内存空间
-
calloc 申请一个大小为size的数组,数组元素类型为 nmemb
-
realloc 为已经申请的内存空间调整大小
-
free释放内存
谁申请谁释放,释放之后将指针指向NULL
#include <stdio.h>
#include <stdlib.h>
int* func(int n, int* p){
p = malloc(n);
*p = 225;
*(p+1) = 522;
return p;
}
int main(){
int* p = NULL;
int* p_back = NULL;
int n = 100;
p_back = func(n, p);
free(p);
/*验证申请得内存空间没有被释放
可以理解为function函数是在栈区,但malloc的空间是堆区,堆区谁申请谁释放
function最后结束,栈区自然释放,但是申请的堆区没有释放
*/
printf("*p = %d\n", *p_back);
printf("*p = %d\n", *(p_back + 1));
//你拿到地址还是可以释放的
free(p_back);
printf("*p = %d\n", *p_back);
return 0;
}