循环结束条件不起作用 - C

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)程序工作得很好.可能是什么原因?

hmj*_*mjd 7

这个:

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在一个出界访问将出现,从而导致未定义的行为.

这个分配的地址tempobj[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)

  • +1特别是检查返回值,这太罕见了. (2认同)