c - strcpy() 函数进入无限循环
问题描述
嗨,我遇到了 strcpy() 函数的问题。这与嵌入式c编程有关。
以下是我的项目中使用的部分代码。基本思想是将字符串(名称)复制到动态分配内存的数组_Items
char *_Items[100];
unsigned char contactname[36];
Memset(name,0,36);
Memset(_Items, 0, sizeof(_Items));
for(count=0; count<10 ; count++)
{
_Items[count] = (char*)malloc((strlen((char*)name)+1)*sizeof(char));
strcpy(_Items[count], (char*)name);
}
....
...function body
....
free(_Items);
在函数的第一次调用中,代码工作正常,但在函数 strcpy() func 的第二次调用中,进入了无限循环。
我无法理解确切的问题是什么。请帮帮我。
解决方案
你在这里有malloc
什么吗?:
char *_Items[100];
没有。那你为什么打电话free(_Items);
?
你在这里有malloc
什么吗?:
for(count=0; count<10 ; count++)
{
_Items[count] = (char*)malloc((strlen((char*)name)+1)*sizeof(char));
是的。那么为什么不free
为循环中的每个项目调用呢?
调用free(_Items)
告诉系统释放一些尚未使用分配的内存malloc
,这是 _undefined 行为,并中断执行的其余部分,可以在任何地方(这就是它的“乐趣”)。
重写你的免费流程:
// allocate
for(count=0; count<10 ; count++)
{
_Items[count] = malloc((strlen((char*)name)+1));
strcpy(_Items[count], (char*)name);
}
....
...function body
....
for(count=0; count<10 ; count++)
{
free(_Items[count]);
}
推荐阅读
- scala - Kafka 流:SessionWindowedSerde 与 TimeWindowedSerde。模棱两可的隐含值
- javascript - (React.js) 嵌套 useContext (全局 > 小组件)
- node.js - 安装服务节点窗口后找不到服务
- curl - 使用 cURL 将文件上传到 Google Drive - access_token 过期问题
- matlab - 我不明白 MATLAB 中关于行和列的这个错误
- tensorflow - 如何从我的架构中加载模型?
- postgresql - 无法创建外键;关系“”不存在
- python - 从许多发件人电子邮件中使用 python 发送 EDM(电子直邮)
- responsive-design - Chrome 的 Galaxy Fold 响应式视图基于什么?
- google-apps-script - 使用“Else If”将数据输入特定列的最后一行