scanf(“%ms”, &p) not working on OSX system

2019-08-01 10:34发布

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?

1条回答
\"骚年 ilove
2楼-- · 2019-08-01 10:38

The manual page forscanf() 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.

查看更多
登录 后发表回答