堆申请的三种alloc用法

三种alloc的用法

#include "stdafx.h"
#include <stdlib.h>
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
{
#if 0
	//malloc 参数为申请的字节数
	short *p = malloc(100);  //size_t size 以字节为单位
	if (NULL == p)           
	{
		printf("malloc error\n");
		return -1;
	}
	free(p);

	//calloc 第一个参数为所需内存单元数量 第二个参数为内存单元的大小 
	int *q = calloc(100, sizeof(int));   //int  a[100]  int *p = a;
	for (int i = 0; i<100; i++)
	{
		printf("%d\n", q[i]);
	}
	free(q);

	//realloc 第一个参数为待扩容的指针(已经申请好的地址) 
	        //第二个参数表示扩容后的内存大小
	int *ptr = realloc(NULL, 400); //第一个参数若为NULL则此时的realloc相当于malloc
	for (int i = 0; i<100; i++)
	{
		printf("ptr[%d] = %d\n", i, ptr[i]);
	}
	free(ptr);
#endif
	//realloc的具体应用
	char *ptr = (char*)malloc(100);
	if (NULL == ptr)
		return -1;

	char *newPtr = (char*)realloc(ptr, 400);
	if (NULL == newPtr)
	{
		printf("realloc error\n");
		return -1;
	}
	strcpy(newPtr, "china");

	//char arr[] = "ladjflasdjfk";
	//scanf("%s",arr);
	//strcpy(arr,"china");

	printf("%s\n", newPtr);
	free(newPtr);
	//开始的ptr就不用free了 free(ptr)
	return 0;
	//realloc 只能扩容,不能缩小空间
	//realloc newPtr ptr 有可能相等,也有可能不等。只使用realloc的返回指针
}


`esp_intr_alloc` 是 ESP32 的 API 函数之一,用于配置和分配中断(interrupt)资源。下面是 `esp_intr_alloc` 函数的使用方法: ```c esp_err_t esp_intr_alloc(int intr_source, int flags, void (*fn)(void*), void* arg, intr_handle_t* handle); ``` 参数说明: - `intr_source`:要分配的中断源的编号,可以在 [ESP32 技术参考手册](https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf) 中找到。例如,GPIO 0 的中断源编号为 `ETS_GPIO_INTR_SOURCE`。 - `flags`:中断标志,指定中断类型和触发方式。例如,可以使用 `ESP_INTR_FLAG_LOWMED` 标志配置中断为低电平触发或下降沿触发,使用 `ESP_INTR_FLAG_EDGE` 标志配置中断为边沿触发。 - `fn`:中断处理函数,当中断发生时会调用该函数。 - `arg`:传递给中断处理函数的参数。 - `handle`:用于保存分配的中断资源句柄。 注意事项: - `esp_intr_alloc` 函数会动态分配中断资源,使用完毕后要使用 `esp_intr_free` 函数释放。 - 中断处理函数需要尽快完成,以避免影响系统的实时性能。 - 为避免中断处理函数在执行时被其他中断打断,可以使用 `portENTER_CRITICAL` 和 `portEXIT_CRITICAL` 函数进行临界区保护。 下面是 `esp_intr_alloc` 函数的一个简单示例: ```c #include "driver/gpio.h" #include "esp_intr_alloc.h" void IRAM_ATTR gpio_isr_handler(void* arg) { uint32_t gpio_num = (uint32_t) arg; printf("GPIO %d interrupt\n", gpio_num); } void app_main(void) { gpio_config_t gpio_cfg = { .pin_bit_mask = (1ULL << GPIO_NUM_0), .mode = GPIO_MODE_INPUT, .pull_up_en = GPIO_PULLUP_ENABLE, .intr_type = GPIO_INTR_NEGEDGE }; gpio_config(&gpio_cfg); intr_handle_t gpio_intr_handle; esp_intr_alloc(ETS_GPIO_INTR_SOURCE, ESP_INTR_FLAG_LOWMED, gpio_isr_handler, (void*) GPIO_NUM_0, &gpio_intr_handle); while(1) { vTaskDelay(1000 / portTICK_RATE_MS); } esp_intr_free(gpio_intr_handle); } ``` 以上代码将 GPIO 0 配置为下降沿触发中断,并将中断处理函数设置为 `gpio_isr_handler`。当 GPIO 0 引脚下降沿触发时,中断处理函数会被调用。注意,由于中断处理函数需要在中断上下文中执行,因此在函数声明前需要添加 `IRAM_ATTR` 关键字。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值