scanf(“%ms",& p)在OSX系统上不起作用 [英] scanf("%ms", &p) not working on OSX system

查看:96
本文介绍了scanf(“%ms",& p)在OSX系统上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在以下代码中使用scanf("%ms, &p)函数.

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;
}

这应该动态分配内存,以避免缓冲区溢出.语法%ms应该用于POSIX系统.但是,在OSX(高Sierra)上,此方法不起作用:代码已执行,scanf结果为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 (n == 0) {
  printf("read: %s\n", p);
  free(p);
}

我看到malloc中存在以下错误:

I see there is the following error in malloc:

malloc: *** error for object 0x7ffeeb91f9c8: pointer being freed was not allocated

那是为什么?

推荐答案

scanf()等人的macOS手册页未提及对该功能的支持.尚未实施.这很麻烦. macOS上对POSIX的支持有时会令人沮丧地落后于时代.

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.

这篇关于scanf(“%ms",&amp; p)在OSX系统上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆