snprintf
提示:文章
文章目录
- 前言
- 一、背景
- 二、
- 三、
- 3.1
- 总结
前言
前期疑问:
本文目标:
一、背景
最近
二、
char countStr[4] = {'\0'};
strncpy(valueBuff, hmi_fireMonitor_gui[i].pName_cn, strlen(hmi_fireMonitor_gui[i].pName_cn));
int rxCount = 0;
rxCount = GetRxCount(i);
snprintf(countStr, sizeof(countStr), "%d", rxCount);
strncpy(valueBuff + 12, countStr, sizeof(countStr));
s_fireMonitor_Items[i].szVariableText = (char *)malloc(sizeof(valueBuff));
strcpy(s_fireMonitor_Items[i].szVariableText, valueBuff);
int t = 2;
上述代码是将RX1字符串存在valueBuff中,然后将数值1200拼到RX1字符串后面。
这里countStr长度过大,程序会内存泄露死机。
如果上面申请字符串长度为4,rxCount为1200, snprintf(countStr, sizeof(countStr), “%d”, rxCount);执行工艺countStr中存的是120,snprintf会在后面补充一个’\0’。
strncpy(valueBuff + 12, countStr, sizeof(countStr));
申请的countStr长度为5,执行上述代码也会死机。要么改成strncpy(valueBuff + 11, countStr, sizeof(countStr));这样就是给valueBuff 留了一个’\0’,或者申请的countStr长度为5,写成strncpy(valueBuff + 11, countStr, strlen(countStr));
在simpleGUI中界面绘制文字中,封装的结构体
typedef struct _ST_SGUI_ITEMS_ITEM_
{SGUI_CSZSTR cszLabelText; // This pointer points to a character array constantSGUI_SZSTR szVariableText; // This pointer points to a character array variable, this member will be used first if existed.struct _ST_SGUI_ITEMS_ITEM_* pstPrev;struct _ST_SGUI_ITEMS_ITEM_* pstNext;
}SGUI_ITEMS_ITEM;
SGUI_CSZSTR是const指针,SGUI_SZSTR是变量指针。如果要现实的是一个不需要改变的字符串,直接可以把const定义的常量字符串指针赋值给SGUI_CSZSTR。如果是字符串需要根据值拼接的,就需要让szVariableText指针指向malloc的内存。实际代码中发现出现malloc申请堆内存失败的情况。就想了个办法如果申请失败,就将"malloc free"常量字符串赋值给cszLabelText,界面上也能显示出。
我就准备专门定义一个宏,#define MALLOC_ERROR “malloc Error”,现在的问题是字符串 "malloc Error"是定义在flash中的吗,问了copilot,答案是是的。另一个问题,MALLOC_ERROR 可以直接复制给常量指针吗?是的,定义了#define MALLOC_ERROR "malloc Error"时,"malloc Error"是一个字符串常量,MALLOC_ERROR类型就是const char*,可以赋值给指针。
strcpy 函数在复制字符串时会自动在末尾添加空字符’\0’。
具体说明
当使用strcpy函数复制字符串时,它会持续复制源字符串的字符(包括结尾的空字符’\0’),直到遇到源字符串的结尾标志’\0’为止。因此,目标字符串的末尾会自动包含这个空字符,无需手动添加。
示例代码
cCopy Code
char dest;
char src = "hello";
strcpy(dest, src);
// 此时dest变为"hello\0",末尾自动包含'\0'
根据现有信息分析,strncpy函数是否在末尾添加\0取决于具体使用情况:
strncpy的补0规则:
- 会补0的情况:当源字符串长度小于指定拷贝长度时,剩余空间会用\0填充12
- 不会补0的情况:当源字符串长度大于或等于指定拷贝长度时,不会自动添加\012
安全使用建议: - 推荐手动补0:无论何种情况,都应在拷贝后手动添加终止符\012
- 封装函数方案:如safe_strncpy在拷贝前预置终止符1
- 替代方案:考虑使用snprintf自动处理终止符2
三、
3.1
总结
未完待续