该程序应该提示输入单词中的字母数量(稍后输入),以便它知道要分配多少空间。它似乎工作正常,但是如果您分配的内存少于存储单词所需的内存似乎并不重要。 这是我必须纠正的错误还是因为这就是指向 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 编程很陌生,所以如果这是一个明显/愚蠢的问题,我很抱歉。 谢谢。
最佳答案
是的,您必须纠正程序中的该错误。
当您分配的内存少于所需的内存,然后访问“额外”内存时,程序将进入未定义行为模式。它可能看起来有效,也可能崩溃,或者可能做任何意想不到的事情。基本上,在写入未分配的额外内存后,没有任何东西得到保证。
[更新:]
我建议从文件中读取任意长度的字符串,代码如下。我无法控制它有点长,但由于标准 C 没有提供很好的字符串数据类型,所以我必须自己完成整个内存管理工作。所以这里是:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** Reads a string from a file and dynamically allocates memory for it. */
int fagetln(FILE *f, /*@out*/ char **s, /*@out*/ size_t *ssize)
{
char *buf;
size_t bufsize, index;
int c;
bufsize = 128;
if ((buf = malloc(bufsize)) == NULL) {
return -1;
}
index = 0;
while ((c = fgetc(f)) != EOF && c != '\n') {
if (!(index + 1 < bufsize)) {
bufsize *= 2;
char *newbuf = realloc(buf, bufsize);
if (newbuf == NULL) {
free(buf);
return -1;
}
buf = newbuf;
}
assert(index < bufsize);
buf[index++] = c;
}
*s = buf;
*ssize = index;
assert(index < bufsize);
buf[index++] = '\0';
return ferror(f) ? -1 : 0;
}
int main(void)
{
char *s;
size_t slen;
if (fagetln(stdin, &s, &slen) != -1) {
printf("%zu bytes: %s\n", slen, s);
}
return 0;
}
关于c - 指向 char 的类型指针的内存分配疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7574677/