[英]Segmentation Fault when finding longest word in input
我編寫了一個程序來查找輸入中最長的單詞。 使用valgrind或在本地運行測試時,我沒有收到任何錯誤,但是我通過分級程序通過電子郵件將代碼發送給我,以報告分段錯誤。
int main(void)
{
char *longest = malloc(1);
size_t size = 1;
do {
char word[20];
if (scanf("%s", word) > 0) {
if (strlen(word) > size) {
longest = realloc(longest,strlen(word)+1);
strcpy(longest,word);
size = strlen(word);
}
}
} while (getchar() != EOF);
printf("%zu characters in longest word: %s\n", strlen(longest),longest);
free(longest);
return 0;
}
您的問題出在char word[20];
行char word[20];
以及scanf
讀取單詞的方式。 從scanf
的角度來看,單詞是任何非空格序列。 例如, realloc(longest,strlen(word)+1);
被視為一個單詞,僅一個單詞就超過20個字符。
您應該使用更強大的功能來讀取單詞並為其分配空間。 最具成本效益的解決方案是使用getline()
讀取行,然后使用strsep()
提取單詞。
在不依賴於POSIX函數的奢華的情況下,僅標准C語言可用於可變字長:
#include <assert.h> // assert()
#include <stddef.h> // size_t
#include <stdbool.h> // bool, true, false
#include <stdlib.h> // EXIT_FAILURE, realloc(), free()
#include <stdio.h> // fscanf(), fgetc(), ungetc(), printf(), fputs()
#include <ctype.h> // isspace()
#include <string.h> // strlen(), strcat(), strcpy()
#define WORD_BUFFER_SIZE 20
#define STRING(value) #value
#define STRINGIFY(value) STRING(value)
// reads and discards whitespace, returns false on EOF
bool skip_ws(FILE *stream)
{
int ch;
while ((ch = fgetc(stream)) != EOF && isspace(ch));
if(!isspace(ch) && ch != EOF) // if it was not whitespace and not EOF
ungetc(ch, stream); // pretend we were never here.
return ch != EOF;
}
bool read_word(char **dst, FILE *stream)
{
assert(dst);
char chunk_buffer[WORD_BUFFER_SIZE + 1];
if (!skip_ws(stream)) // if we encounter EOF before any other non-whitespace
return false;
// read chunk by chunk
for (size_t i = 0; fscanf(stream, "%" STRINGIFY(WORD_BUFFER_SIZE) "s", chunk_buffer) == 1; ++i)
{
size_t chunk_length = strlen(chunk_buffer);
// adjust *dst's size
char *tmp = realloc(*dst, (i * WORD_BUFFER_SIZE + chunk_length + 1) * sizeof(*tmp));
if (!tmp) {
free(*dst);
*dst = NULL;
return false;
}
*dst = tmp;
if (i == 0) // zero terminate it if it is the first junk
**dst = '\0'; // for strcat() to behave well.
strcat(*dst, chunk_buffer); // add the current chunk to *dst.
int next_char = fgetc(stream);
ungetc(next_char, stream);
if (chunk_length < WORD_BUFFER_SIZE || isspace(next_char) || next_char == EOF)
return true;
}
return true;
}
int main(void)
{
char *word = NULL;
char *longest_word = NULL;
size_t longest_length = 0;
while (read_word(&word, stdin)) {
size_t length = strlen(word);
if (length > longest_length) {
char *tmp = realloc(longest_word, (length + 1) * sizeof *tmp);
if (!tmp) {
fputs("Not enough memory. :(\n\n", stderr);
free(longest_word);
free(word);
return EXIT_FAILURE;
}
longest_length = length;
longest_word = tmp;
strcpy(longest_word, word);
}
}
free(word);
printf("%zu characters in the longest word: \"%s\"\n\n", longest_length, longest_word);
free(longest_word);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.