我有关于动态数组的作业,因此我试图了解它如何与简单程序一起工作。

#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;
}


当我通过从stdin读取来使“ cnt”等于5时,尽管满足结束条件,程序仍将永远运行。但是,当我通过分配它使“ cnt”等于5时,在程序的开始(而不是通过使用scanf),该程序就可以正常工作。
这可能是什么原因?

最佳答案

这个:

scanf("%d",cnt);


应该:

/* 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)
{
}


因为scanf()需要cnt的地址。

也:


Don't cast result of malloc()
保证sizeof(char)1,因此可以从malloc()的空间计算中省略。
检查malloc()的结果以确保已分配内存。
free()什么是malloc() d。
通过指定要读取的最大字符数,防止使用scanf("%s")导致缓冲区溢出,该字符数必须比目标缓冲区少1个字符,以留出空格来终止空字符。在您的情况下scanf("%1000s", temp)
没有对数组obj上的越界访问的保护。 while循环的终止条件是i<cnt,但是如果cnt > 5将会发生越界访问,从而导致不确定的行为。


这会将temp的地址分配给obj[i]

obj[i]=temp;


它不会复制(并导致内存泄漏)。使用strcpy()代替:

obj[i] = malloc(strlen(temp) +1 );
if (obj[i])
{
    strcpy(obj[i], temp);
}

07-24 09:46
查看更多