的sprintf()具有自动内存分配? [英] sprintf() with automatic memory allocation?

查看:667
本文介绍了的sprintf()具有自动内存分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一个的sprintf() - 样实现,它会自动分配所需的存储功能的。所以,我想说

I'm searching for a sprintf()-like implementation of a function that automatically allocates required memory. So I want to say

char* my_str = dynamic_sprintf( "Hello %s, this is a %.*s nice %05d string", a, b, c, d );

和my_str检索分配的内存保存此的sprintf()的结果。

and my_str retrieves the adress of an allocated memory that holds the result of this sprintf().

在另一个论坛,我读这可以这样解决:

In another forum, I read that this can be solved like this:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main()
{
    char*   ret;
    char*   a = "Hello";
    char*   b = "World";
    int     c = 123;

    int     numbytes;

    numbytes = sprintf( (char*)NULL, "%s %d %s!", a, c, b );
    printf( "numbytes = %d", numbytes );

    ret = (char*)malloc( ( numbytes + 1 ) * sizeof( char ) );
    sprintf( ret, "%s %d %s!", a, c, b );

    printf( "ret = >%s<\n", ret );
    free( ret );

    return 0;
}

但是,这immediatelly导致时的sprintf()与NULL指针调用段错误。

But this immediatelly results in a segfault when the sprintf() with the NULL-pointer is invoked.

因此​​,任何想法,解决方案或建议吗?小型实施的sprintf()的 - 就像分析器被放置在公共领域应该已经足够多,那么我能得到它自己做

So any idea, solution or tips? A small implementation of a sprintf()-like parser that is placed in the public domain would already be enought, then I could get it myself done.

非常感谢!

推荐答案

GNU和BSD了 asprintf 并vasprintf被设计来做到这一点你。它会找出如何分配的内存,为您和将返回null任何内存分配错误。

GNU and BSD have asprintf and vasprintf that are designed to do just that for you. It will figure out how to allocate the memory for you and will return null on any memory allocation error.

asprintf做正确的事就分配字符串 - 它首先测量尺寸,然后它会尝试使用malloc分配。如果做不到这一点,则返回null。除非你有自己的内存分配系统,precludes的使用malloc,asprintf是这个职位的最佳工具。

asprintf does the right thing with respect to allocating strings -- it first measures the size, then it tries to allocate with malloc. Failing that, it returns null. Unless you have your own memory allocation system that precludes the use of malloc, asprintf is the best tool for the job.

在code看起来像:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main()
{
    char*   ret;
    char*   a = "Hello";
    char*   b = "World";
    int     c = 123;

    ret = asprintf( "%s %d %s!", a, c, b );
    if (ret == NULL) {
        fprintf(stderr, "Error in asprintf\n");
        return 1;
    }

    printf( "ret = >%s<\n", ret );
    free( ret );

    return 0;
}

这篇关于的sprintf()具有自动内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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