【问题标题】:strcpy() function is enterning into infinite loop [closed]strcpy()函数正在进入无限循环[关闭]
【发布时间】:2018-05-21 08:38:19
【问题描述】:

我遇到了 strcpy() 函数的问题。这与嵌入式c编程有关。

以下是我的项目中使用的部分代码。基本思路是将string(name)复制到动态分配内存的数组_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 进入无限循环。

我无法理解确切的问题是什么。请帮帮我。

【问题讨论】:

  • namecontactnameMemsetmemset ?你需要一个minimal reproducible example,因为这里似乎没有什么太大的问题(除了free(_Items),它可能会使应用程序崩溃
  • 也就是说,如果你调用free(_Items);,你会破坏你的内存程序并在剩余的运行中获得未定义的行为。你必须循环 _Items 的每个元素来释放它。
  • 在 C 中不需要转换 malloc() 的结果。
  • 所以乘以 sizeof(char) 即为 1。
  • free(_Items); 导致未定义的行为,不要这样做

标签: c embedded dynamic-programming


【解决方案1】:

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]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2014-01-28
    • 2021-12-31
    相关资源
    最近更新 更多