简体   繁体   English

在C语言中,为什么我们需要将char *强制转换为void?

[英]In C, why do we need to cast char* to void?

I read a unit test, that checks for invalid free or double-free: 我读了一个单元测试,它检查无效的免费或双重免费:

int main() {
    char *a = (char*) my_malloc(200);
    char *b = (char*) my_malloc(50);
    char *c = (char*) my_malloc(200);
    char *p = (char*) my_malloc(3000);

    (void) a, (void) c;

    memcpy(p, b - 200, 450);
    my_free(p + 200);
    printstatistics();
}

Why do we need to cast char* to void and what happens in memory when we do this cast? 为什么我们需要将char*void以及执行此强制转换时内存中发生了什么?

(void) a, (void) c;

is a common way to get rid of compiler warnings about unused variables. 是摆脱有关未使用变量的编译器警告的常用方法。 Since those two variables are initialised only and not used later, most compilers would issue warnings about it. 由于这两个变量仅被初始化,以后不使用,因此大多数编译器都会发出有关它的警告。 Since this is apparently some kind of a test of memory allocation they are not used on purpose, so someone decided to silence warnings. 由于这显然是对内存分配的某种测试,因此它们不是故意使用的,因此有人决定静音警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM