I am trying to use scanf("%ms, &p)
function in the following code.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *p;
int n;
n = scanf("%ms", &p);
if (n == 1) {
printf("read: %s\n", p);
free(p);
}
else {
printf( "%d, No matching characters\n", n);
}
return 0;
}
This should allocate memory dynamically avoiding buffer overflow. The syntax %ms
should be for POSIX systems. However on OSX (High Sierra), this is not working: the code is executed, the scanf
result is 0 and it does not stop the program to wait for user input.
If I do:
if (n == 0) {
printf("read: %s\n", p);
free(p);
}
I see there is the following error in malloc
:
malloc: *** error for object 0x7ffeeb91f9c8: pointer being freed was not allocated
Why is that?
The manual page for
scanf()
et al for macOS does not mention support for the feature. It isn’t implemented. It is a nuisance. The support for POSIX on macOS is occasionally frustratingly behind the times.