[英]dereferencing a null pointer when creating socket in C
I'm trying to convert a program developed in linux to visual studio.我正在尝试将在 linux 中开发的程序转换为 Visual Studio。 The program is in C language.
程序是C语言的。 I tried replacing the socket functions from socket.h to the ones from visual studio.
我尝试将 socket.h 中的套接字函数替换为 Visual Studio 中的套接字函数。 This is what I have so far.
这是我到目前为止。
#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;
}
}
I didn't get an error in linux even though the code is very similar.即使代码非常相似,我也没有在 linux 中收到错误消息。 I'm getting the following error when I build:
我在构建时收到以下错误:
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
I would appreciate any suggestions thanks.我将不胜感激任何建议谢谢。
I added an init function for winsock.我为 winsock 添加了一个 init 函数。 Looks like that was the problem because it built fine now.
看起来这就是问题所在,因为它现在构建得很好。 Can someone verify?
有人可以验证吗? Thanks.
谢谢。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.