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

南笙酒味 提交于 2019-12-24 14:11:55

问题


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:


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.



来源:https://stackoverflow.com/questions/54461111/scanfms-p-not-working-on-osx-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!