首页 > 解决方案 > 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 的第二次调用中,进入了无限循环。

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

标签: cembeddeddynamic-programming

解决方案


你在这里有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]);
}

推荐阅读