【发布时间】:2011-11-26 08:14:21
【问题描述】:
这个程序应该提示输入单词中的字母数量(稍后输入),因此它知道要分配多少空间。它似乎工作正常,但是如果您分配的内存少于存储单词所需的内存,这似乎并不重要。 这是我必须纠正的错误还是因为指向 char (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));
}
现在我的疑问是:为什么我可以声明一个空的 char 数组(char aux[] = ""),然后使用没有错误的“额外”内存(在 valgrind 输出中)然而 char *aux = "";给我一个分段错误? 我对 C 编程很陌生,所以如果这是明显/愚蠢的问题,我很抱歉。 谢谢。
【问题讨论】:
-
scanf("%s", word)本质上是不安全的。如果用户输入的字符多于您分配的空间,无论多多,都会导致缓冲区溢出。
标签: c pointers memory-management malloc arrays