我试图用stgets()从stdin读取行,我想在我的函数中使用fgets(),我认为这是问题所在。字符串最长可达1024个字符。当我运行此代码时,我得到"分段错误(核心转储)"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1025
void print_fgets();
int main()
{
print_select();
return 0;
}
void print_select()
{
char *str;
int length;
while (fgets( str, MAX_SIZE, stdin)!=NULL)
{
length=strlen(str);
if (length==MAX_SIZE-1 && str[length-1]!='\n')
{
printf("Error, line overeached buffer!\n");
return 1;
}
if (str[length-1]=='\n')
str[length-1]='\0';
printf("%s\n", str);
}
}
答案 0 :(得分:0)
问题是您尝试写入str
指针指向的位置。
最初它会指向一些垃圾地址(由于char *str
没有被初始化)。
您可以尝试更改基于堆栈的解决方案:
/* This is just a pointer */
char *str;
为:
/* This is a character array (on the stack) of size MAX_SIZE, initialized to zero */
char str[MAX_SIZE] = {0};
或者,如果您想为数组动态分配内存,请执行以下操作:
char *str;
str = calloc(1, MAX_SIZE);
if (str == NULL) {
/* Failed to allocate memory */
}
... Your code
free(str); /* You should always free dynamically allocated memory when you are done with it */
str = NULL; /* It's a good practice to point your pointer to NULL after it's free'd */
不要忘记像0
一样的数组索引,然后转到MAX_SIZE - 1
(在你的情况下)和NUL终止(字符串必须以它结尾)。
答案 1 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1025
int print_select(); /* Use correct name (instead of print_fgets()) */
int main()
{
print_select();
return 0;
}
int print_select() /* Fix. Dhould return int if you have a return <int> statement. */
{
char str[MAX_SIZE]; /* Initialize static memory. */
int length;
while (fgets( str, MAX_SIZE, stdin)!=NULL)
{
length=strlen(str);
if (length==MAX_SIZE-1 && str[length-1]!='\n')
{
printf("Error, line overeached buffer!\n");
return 1;
}
if (str[length-1]=='\n')
{
str[length-1]='\0';
}
printf("%s\n", str);
}
return 0; /* Function may not be returning an int. Return it in those cases. */
}