Reputation: 703
I have problem in program with locale and reading from stdin with fgetws
function.
#include <stdio.h>
#include <locale.h>
#include <wchar.h>
static const int N = 2;
int main(void) {
setlocale(LC_ALL, "");
wchar_t data[N];
fgetws(data, N, stdin);
printf("%ls\n", data);
/* fclose(stdin); */
return 0;
}
When input is long enough (5 or more chars) I get segfault if I don't close stdin
before return
. Why is that? What is wrong with this program?
Upvotes: 0
Views: 87
Reputation: 154146
Suspect fgetws(data, 2, stdin)
is broken.
fgetws()
, using such a small buffer should, at most, read 1 wchar_t
from stdin
and append a termanting (wchar_t) '\0'
.
As usual, when code fails mysteriously, best to check return from the functions to see if they are as expected.
#include <stdio.h>
#include <locale.h>
#include <wchar.h>
#include <assert.h>
#include <stdio.h>
#include <locale.h>
#include <wchar.h>
static const int N = 2;
int main(void) {
char *p = setlocale(LC_ALL, "");
assert(p);
wchar_t data[N];
wchar_t *s = fgetws(data, N, stdin);
assert(s);
int i = printf("%ls\n", data);
assert(i == 2);
i = fclose(stdin);
assert(i == 0);
return 0;
}
Upvotes: 1