问题记录--sscanf踩内存

1. 问题描述

使用sscanf函数将字符串对变量赋值的时候,会把当前变量地址后面的变量内容修改掉。

1. 变量定义

uint8_t TargetType = 0x00;	//0x00 WallE; 0x01 Elin
uint8_t val = 0;			//string length

uint8_t SLAVE_ADDR = 0x4C;
uint8_t TxData[12] = { 0x00};

uint8_t buffer[4096] = {0x00};
uint8_t mem_data[8];
uint8_t str[13];
uint8_t *TxBackData = (void *)0;
int			i=0;
uint8_t Buf[11] = "slave 0x4C";

2. 变量修改

TxBackData = &buffer[0];	//指针指向数组
sscanf((const char *)(Buf+5), "%x", (char *)&SLAVE_ADDR);	//将0x4C赋值给变量SLAVE_ADDR ,结果发现TxBackData 指针被修改了

2. 原因

待查…

3. 问题复现

下面是vscode上运行的代码,由于和单片机的内存管理不一样,所以用value变量来替代指针,但同样出现value值被修改的现象。

#include 
#include 
#include 
uint8_t TargetType = 0x00;	//0x00 WallE; 0x01 Elin
uint8_t val = 0;			//string length

uint8_t SLAVE_ADDR = 0x4C;
uint8_t value = 2;
uint8_t *TxBackData = (void *)0;
uint8_t TxData[12] = { 0x00};

uint8_t buffer[4096] = {0x00};
uint8_t mem_data[8];
uint8_t str[13];

int			i=0;
uint8_t Buf[11] = "slave 0x4C";

int main()
{
    TxBackData = &buffer[0];	//指针指向数组
    printf("SLAVE_ADD addr = %p,value addr = %p, RTxBackData addr = %p\r\n",&SLAVE_ADDR, &value, &TxBackData);
    buffer[0] = 'C';
    sscanf((const char *)(Buf+5), "%x", (char *)&SLAVE_ADDR);	//将0x4C赋值给变量SLAVE_ADDR ,结果发现TxBackData 指针被修改了
    printf("slave 0x%x,val = %d, TxBackData[0] = %c\n", SLAVE_ADDR,value, TxBackData[0]);
    return 0;
}

代码运行结果:

SLAVE_ADD addr = 00007ff6fff0f000,value addr = 00007ff6fff0f001, RTxBackData addr = 00007ff6fff13048

slave 0x4c,val = 0, TxBackData[0] = C

你可能感兴趣的:(嵌入式开发,c语言,内存管理,嵌入式)