为什么realloc()在为C++编译时表现出神秘的不同

Why is realloc() mysteriously behaving differently when compiled for C++?

本文关键字:realloc 在为 编译 C++ 为什么      更新时间:2023-10-16

我有以下函数,我以前在C程序中使用过很多次:

/**
    Splits a given string into an array of strings using given delimiters.
    @param input_string
        The string to be split.
    @param delimiters
        The characters that will be used as delimiters.
    @return
        The components of the split string followed by @c NULL , or only
        @c NULL if sufficient memory fails to allocate for the returned array.
 */
char **split(char *input_string, const char *delimiters) {
    char **components = NULL;
    int components_count = 0;
    char *component = strtok(input_string, delimiters);
    while (component) {
        ++components_count;
        // |components| is reallocated to accomodate |component|. If
        // |realloc()| fails, |NULL| is returned.
        components = realloc(components, sizeof(char *) * components_count);
        if (!components) return NULL;
        components[components_count - 1] = component;
        component = strtok(NULL, delimiters);
    }
    // |components| is reallocated once more to accomodate an additional
    // |NULL|. Only |NULL| is returned in |realloc()| fails.
    components = realloc(components, sizeof(char *) * (components_count + 1));
    if (!components) {
        return NULL;
    }
    components[components_count] = NULL;
    return components;
}

我最近刚刚将该函数添加到C++项目中,以便在需要处理C字符串的情况下使用。在编译时,我现在得到以下错误:

error: assigning to 'char **' from incompatible type 'void *'
        components = realloc(components, sizeof(char *) * components_count);
error: assigning to 'char **' from incompatible type 'void *'
    components = realloc(components, sizeof(char *) * (components_count + 1));

我完全不知道该怎么处理这些错误。就我而言,我所做的在C++中应该是合法的,因为它在C中总是很好用。有什么见解吗?

如果有帮助的话,我将在OSX上使用clang++作为编译器,但这段代码也有望在Ubuntu上使用g++进行编译。

在C和C++上并非所有东西都必须相同;CCD_ 1和CCD_。

  1. 您不必在C中显式地强制转换void pointer,它将自动完成,就像您的示例一样
  2. 在C++中,无论是在malloc还是在realloc函数中,都必须显式地强制转换该指针

这两种语言之间有很大的区别,不要认为一切都是理所当然的。

在这个链接中,C和C++在基本内容上的一些差异在这里陈述;也许值得一读。

http://www.cprogramming.com/tutorial/c-vs-c++.html

或者这个(由评论建议):

http://david.tribble.com/text/cdiffs.htm

C++不允许void*指针隐式转换为其他指针。此外,C和C++是完全不同的语言,所以并不是所有的C都能在C++上工作,因为它是一种不同的语言。

但是,显式强制转换realloc()结果应该可以。

将C代码与C++代码隔离开来。它们是不同的语言。把C当作可以用C++运行一样对待,就像把繁体中文当作可以用简体中文运行一样有意义。如果你正在编写一个用C++编译器编译的程序,它可能看起来与你用C编译器编译的软件非常不同。

尽管如此,有时您可能希望将一些C代码(或汇编代码,或其他任何代码)链接到您的C++代码。如果您使用的编译器具有兼容的ABI,那么每个语言的过程可能都是相似的。我将使用的示例是gccg++

使用C编译器(例如malloc0)编译C代码,但不使用链接过程(例如使用-c标志)。例如:gcc -c split.c

使用C++编译器编译C++代码,并将C编译器生成的目标代码链接到其中。例如:g++ main.cpp split.o