C – 在函数中使用fgets()从stdin读取行
我试图用stgets()从stdin读取行,我想在我的函数中使用fgets(),我认为这是问题所在。 字符串最长可达1024个字符。 当我运行此代码时,我得到“Segmentation fault(core dumped)”
#include #include #include #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); } }
问题是您尝试写入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终止(字符串必须以它结束)。
#include #include #include #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 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. */ }