如何检测一个字符串字面传递给C中的函数? [英] How to detect the passing of a string literal to a function in C?

查看:99
本文介绍了如何检测一个字符串字面传递给C中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现Perl的用C格格()函数的eqivilent版本,我所遇到的其中literal字符串传递作为参数会导致一个角落的情况下分段错误(理应如此)。

示例格格(一些文字字符串\\ n);

有在C99中定义的方法来检测羯羊或不是我的函数传递一个字符串字面量,以便我能收益而不试图NUL出来?

 的char *格格(字符* S)
{
    字符* TEMP = S;    如果(S&安培;&放大器; * S)
    {
        S + = strlen的(S) - 1;
        如果(* S =='\\ n')
        {
            * S ='\\ 0';
        }
    }
    返回温度;
}


解决方案

  

是否有C99定义的方法来检测羯羊或不是我的函数传递一个字符串字面量,这样我可以不尝试NUL它返回?


您不应该的。

您的API不应该试图捏造事情来电,只有把它打破以后。 如果主叫方打破了规则,他们应该找出,然后有。

如果调用者传递一个非可变的字符串给需要一个可变的一个,它的的段错误的功能。还有什么是不好的设计。

(附录:最好的设计,当然会返回字符串呼叫者负责释放的复印件)

I am trying to implement an eqivilent version of perl's chomp() function in C and I have come across a corner case where a string literal passed as the argument will cause a segmentation fault (rightfully so).

Example chomp("some literal string\n");

Is there a defined way in C99 to detect wether or not my function was passed a string literal so that I can return without attempting to NUL it out?

char* chomp(char *s)
{
    char *temp = s;

    if (s && *s)
    {
        s += strlen(s) - 1;
        if (*s == '\n')
        {
            *s = '\0';
        }
    }
    return temp;
}

解决方案

Is there a defined way in C99 to detect wether or not my function was passed a string literal so that I can return without attempting to NUL it out?

You shouldn't.

Your API shouldn't attempt to fudge things for the caller, only to have it break later on. If the caller breaks the rules, they should find out then and there.

If the caller passes a non-mutable string to a function that expects a mutable one, it should segfault. Anything else is bad design.

(Addendum: The best design, of course, would be to return a copy of the string that the caller is responsible for freeing.)

这篇关于如何检测一个字符串字面传递给C中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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