执行
当我运行代码时,它显示realloc()
无效指针错误。
input()
函数有什么问题吗?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
char *input(void)
{
int n = 1;
char *str = malloc(sizeof(char));
*str = ' ';
while((*str=getchar())!='n')
{
n++;
str = realloc(str,sizeof(char)*n);
str++;
}
return str;
}
int main(int argc, char const *argv[])
{
char *str = input();
printf("%s",str);
free(str);
return 0;
}
您会犯一些错误:
-
返回字符串的末尾,而不是开头。
-
realloc
需要原始地址(见Thomas的回答( -
CCD_ 4可以返回新的地址
-
您不会终止字符串。
以下修复了这些错误,并包含了一些建议:
char *input(void)
{
size_t i=0;
int c;
char *str = malloc(1);
if (!str) return 0;
while((c=getchar())!=EOF && c!='n')
{
str[i]= c;
if ((newstr = realloc(str,i+1))==0)
break; // out of memory: return what we have
str= newstr;
i++;
}
str[i]= ' ';
return str;
}
str++
后,指针不再指向已分配字符串的开头。realloc
需要原始指针,而不是指向所分配数据内部某个位置的指针。
一种没有冗余调用和完整错误检查的方法:
#include <stdio.h>
#include <stdlib.h>
char *input(void)
{
size_t n = 0;
char * str = NULL;
do
{
++n;
{
void * pv = realloc(str, (n + 1) * sizeof *str);
if (NULL == pv)
{
perror("realloc() failed");
break;
}
str = pv;
}
{
int result = getchar();
if (EOF == result)
{
if (ferror(stdin))
{
fprintf(stderr, "getchar() failedn");
}
--n;
break;
}
str[n - 1] = result;
}
} while ('n' != str[n - 1]);
if (NULL != str)
{
str[n] = ' ';
}
return str;
}
int main(int argc, char const *argv[])
{
int result = EXIT_SUCCESS; /* Be optimistic. */
char * str = input();
if (NULL == str)
{
result = EXIT_FAILURE;
fprintf(stderr, "input() failedn");
}
else
{
printf("input is: '%s'n", str);
}
free(str);
return result;
}