【问题标题】:dereferencing a null pointer when creating socket in C在 C 中创建套接字时取消引用空指针
【发布时间】:2021-12-11 10:42:28
【问题描述】:

我正在尝试将在 linux 中开发的程序转换为 Visual Studio。该程序是C语言的。我尝试将 socket.h 中的套接字函数替换为 Visual Studio 中的套接字函数。这是我目前所拥有的。

#define _CRT_SECURE_NO_WARNINGS
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x6000
#endif
#undef UNICODE
#define UNICODE
#undef _WINSOCKAPI_
#define _WINSOCKAPI_

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

#define _CRT_SECURE_NO_WARNINGS

struct the_socks
{
    int sock_file_d;
    struct sockaddr_in my_addr;
};

int  main()
{
    struct the_socks* my_sock;
    int state = -1;

    my_sock = (struct the_socks*)malloc(sizeof(struct the_socks));

    struct sockaddr_in client_n, server_n;

    if ((my_sock->sock_file_d = socket(AF_INET, SOCK_STREAM, 0)) >= 0)
    {
        state = 0;
    }
}

即使代码非常相似,我在 linux 中也没有遇到错误。构建时出现以下错误:

Severity    Code    Description Project File    Line    Suppression State   Detail Description
Warning C6011   Dereferencing NULL pointer 'my_sock'.   Project3    C:\Users\stuff\source\main.c    33  

如果有任何建议,我将不胜感激。

【问题讨论】:

标签: c sockets null-pointer


【解决方案1】:

我为winsock 添加了一个初始化函数。看起来这就是问题所在,因为它现在构建得很好。有人可以验证吗?谢谢。

#define _CRT_SECURE_NO_WARNINGS
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x6000
#endif
#undef UNICODE
#define UNICODE
#undef _WINSOCKAPI_
#define _WINSOCKAPI_

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

#define _CRT_SECURE_NO_WARNINGS

#pragma comment(lib,"ws2_32.lib") //Winsock Library

struct the_socks
{
    int sock_file_d;
    struct sockaddr_in my_addr;
};

int  main()
{
    WSADATA wsa;

    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    printf("Initialised.");


    struct the_socks* my_sock;
    int state = -1;

    my_sock = (struct the_socks*)malloc(sizeof(struct the_socks));

    struct sockaddr_in client_n, server_n;

    if ((my_sock->sock_file_d = socket(AF_INET, SOCK_STREAM, 0)) >= 0)
    {
        state = 0;
    }
    //do other stuff
    return 0;
}

【讨论】:

  • 为什么不直接在栈上声明 my_sock 呢?这样就不需要 malloc() 或指针解引用,也没有内存泄漏的机会。
  • 就像替换行来构造 the_socks my_sock;如果 ((my_sock.sock_file_d = socket(AF_INET, SOCK_STREAM, 0)) >= 0)
  • 是的,就像那样。
  • :0 感谢您的帮助。
  • 虽然在 Windows 上添加 WSAStartup() 是必需的,但简单地添加它并不能解决 NULL 取消引用。我不相信原始错误消息是正确的,因为 malloc() 在这样一个简单的程序中几乎不可能失败,这将是 my_sock 可能为 NULL 的唯一方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 2011-05-27
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多