该程序应该提示输入一个单词中的字母数(稍后输入),以便知道需要分配多少空间。它似乎可以正常工作,但是如果分配的内存少于要存储的单词所需的内存量,似乎并不重要。 这是一个错误,我必须纠正或是因为这是如何指针字符(char *)的作品?内存分配怀疑类型指针字符
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int a = 0;
printf("Enter the size of the word(0=exit) :");
scanf("%d",&a);
if(a==0){return 0;}
else
{
char *word = (char *)malloc(a*sizeof(char) + 1);
if(word == NULL)
{
fprintf(stderr,"no memory allocated");
return 1;
}
printf("Reserved %d bytes of space (accounting for the end-character).\nEnter your word: ", a*sizeof(char) + 1);
scanf("%s", word);
printf("The word is: %s\n", word);
}
return 0;
}
好吧,我想我可能有固定的,这样一来,用Valgrind的运行表明,没有它前面显示的错误。
char aux[]="";
scanf("%s", aux);
if(strlen(aux)>(a*sizeof(char) + 1))
{
fprintf(stderr,"Word bigger than memory allocated\nExiting program\n");
return 1;
}
else
{
strcpy(word,aux);
printf("The word is: %s\nAnd is %d characters long\n", word, strlen(word));
}
现在我的疑问是:为什么我可以声明一个空字符数组(字符AUX [] =“”),然后用“没有错误的额外”的内存(在Valgrind的输出),但字符* AUX = “”;给我一个分段错误? 我对C编程非常陌生,所以我很抱歉,如果这是明显/愚蠢的问题。 谢谢。
'scanf(“%s”,word)'本质上是不安全的。如果用户输入的字符多于您为其分配空间的字符数量,则会出现缓冲区溢出。 –