c - 关于关于强制转换的编译器警告

标签 c linux gnu

我正在测试如下示例代码,为什么在 linux ubuntu 16-4 上使用 gcc 5.6 编译时收到警告?

~/c$ gcc malloc.c 
malloc.c: In function ‘main’:
malloc.c:17:14: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
     if(number= malloc(50*sizeof(int) )== NULL)

这是我的代码:

#include "stdlib.h"
#include "stdio.h"

int main()
{
    char* str;
    int * number;
    if((str= (char *)malloc(100) )== NULL)
    {
        printf("malloc fail \n");
        exit(1);
    }

    printf ("sting was allocaed \n");
    if(number= malloc(50*sizeof(int) )== NULL)
    {
        printf("malloc fail \n");
        exit(1);
    }

    printf ("int was allocaed \n");
    return 0;
}

最佳答案

这里

number= malloc(50*sizeof(int) )== NULL 

您将 mallocNULL 返回的比较结果分配给 number,因为 == 的优先级高于 =

幸运的是,编译器捕获了这一点,因为 number 是一个指针。

你需要做:

(number = malloc(50*sizeof(int)) )== NULL

注意:当您有疑问时,请插入一些括号。它不花一毛钱。

此外,您很幸运,编译器以默认警告级别捕获了此问题。将来,始终在启用所有警告的情况下进行编译 -Wall 并且可能添加 -Wextra -pedantic

请注意,您的第一次分配(几乎)没问题:

if((str= (char *)malloc(100) )== NULL)

除了[您不应该在 C 中转换 malloc 的输出][1],因此:

if((str= malloc(100) )== NULL)

甚至更好(是的,无需乘以 sizeof(char),它始终为 1)

关于c - 关于关于强制转换的编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46647439/

相关文章:

将结构从指针类型变量复制到非指针类型变量

c - 需要使用 openssl 加密和解密文件的示例 C 代码

将 unsigned long long 的最低字节复制到 C 中的数组

linux - Cron 运行 .sh 文件没有任何结果

c - 访问单个结构成员是否会将整个结构拉入缓存?

binary - 在GNU ld链接程序脚本中包含二进制文件

c - 左值错误和数组指针

css - 使用 SED 和 RegEx 将下划线放回数百个 CSS 文件的链接中

makefile - GNU Make 中的条件依赖

python-2.7 - GNU Parallel 在大文件上运行 Python 脚本