Ka *_*tsu -1 c arrays loops dynamic
我有一个关于动态数组的作业,因此我试图理解它如何与简单的程序一起工作.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int cnt,i=0;
char temp[1001];
char *obj[5];
scanf("%d",cnt);
while(i<cnt){
scanf("%s",temp);
obj[i]=malloc(sizeof(char)*(strlen(temp)+1));
obj[i]=temp;
printf("%s\n",obj[i]);
printf("%d\n",i);
i++;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我得到"cnt"等于5时,通过从stdin读取,程序将永远运行,尽管结束条件满足.但是当我得到"cnt"等于5时,通过分配它,在程序的最开始(不是通过使用scanf)程序工作得很好.可能是什么原因?
这个:
scanf("%d",cnt);
Run Code Online (Sandbox Code Playgroud)
应该:
/* Always check return value of scanf(),
which returns the number of assignments made,
to ensure the variables have been assigned a value. */
if (scanf("%d",&cnt) == 1)
{
}
Run Code Online (Sandbox Code Playgroud)
如scanf()需要的地址 cnt.
也:
malloc().sizeof(char)保证1可以从空间计算中省略malloc().malloc()以确保分配内存.free()无论如何malloc().scanf("%s")通过指定要读取的最大字符数来防止缓冲区溢出,该字符数必须比目标缓冲区少一个,以便为终止空字符留出空间.在你的情况下scanf("%1000s", temp).obj.该while循环的终止条件i<cnt,但如果cnt > 5在一个出界访问将出现,从而导致未定义的行为.这个分配的地址temp到obj[i]:
obj[i]=temp;
Run Code Online (Sandbox Code Playgroud)
它不会复制(并导致内存泄漏).strcpy()改为使用:
obj[i] = malloc(strlen(temp) +1 );
if (obj[i])
{
strcpy(obj[i], temp);
}
Run Code Online (Sandbox Code Playgroud)