简体   繁体   English

函数调用时出现分段错误

[英]Segmentation fault while function call

I got a struct Chat 我有一个结构聊天

struct Chat
{
    int m_FD;
    int m_BindPort;
    char m_NameLength;
    char* m_Name;
    char m_PeerCount;
    char** m_PeerList;

} typedef Chat_t;

i'm initializing it with this function: 我正在使用此功能对其进行初始化:

int chat_init(Chat_t* this, unsigned int nameLen, char* name, unsigned short int bindPort, unsigned int peerCount, char** peerList)
{
    this->m_NameLength = nameLen;
    this->m_Name = malloc(sizeof(char) * (nameLen+1));
    strcpy(this->m_Name, name);
    this->m_BindPort = bindPort;
    this->m_PeerCount = peerCount;
    this->m_PeerList = malloc(sizeof(char*) * peerCount);
    for(int i=0; i<peerCount; i++)
    {
        this->m_PeerList[i] = malloc(sizeof(char) * 16); // enough for xxx.xxx.xxx.xxx\0
        strcpy(this->m_PeerList[i], peerList[i]);
    }

    //Socket initialization for TCP connection...
    //Commenting this out doesn't change anything so i'm hiding it for simplification

    return 0;

}

After that i'm calling a second function 之后,我要调用第二个函数

int chat_communicate(Chat_t* this)
{
    printf("2\n");
    fflush(stdout);

    //Some stuff that doesn't matter because it isn't even called

    return retVar;
}

in main like this 像这样

void main(void)
{
    char* peerList[1];
    char username[USERNAME_MAX_LEN];
    int initRet;
    int loopRet;
    Chat_t chat;

    peerList[0] = "192.168.2.2";

    memset(username, 0, USERNAME_MAX_LEN);

    printf("Please enter your user name: ");
    scanf("%s", username);

    username[USERNAME_MAX_LEN-1] = 0;

    initRet = chat_init(&chat, strlen(username), username, 1234, 1, peerList);

    printf("File Descriptor: %d\n", chat.m_FD);
    printf("Binding Port: %d\n", chat.m_BindPort);
    printf("Name Length: %d\n", chat.m_NameLength);
    printf("Name: %s\n", chat.m_Name);
    printf("Peer Count: %d\n", chat.m_PeerCount);
    for(int i=0; i< chat.m_PeerCount; i++)
    {
      printf("Peer[%d]: %s\n", i, chat.m_PeerList[i]);
    }

    printf("1");
    ret = chat_communicate(&chat);

    //Even more Stuff that isn't even called

}

My program outputs the following 我的程序输出以下内容

File Descriptor: 3
Binding Port: 1234
Name Length: 4
Name: User
Peer Count: 1
Peer[0]: 192.168.2.2
1
Segmentation Fault

It compiles without errors or even warnings. 它编译时没有错误甚至警告。

You can also assume that every string is null-Terminated The stuff i replaced with comments itn't that complicated but just too much to show. 您还可以假设每个字符串都是以null终止的。我用注释代替的内容并不那么复杂,但显示起来实在太多。

Every value inside the struct is printed with printf right before but when passing this very struct per reference the application crashes. struct内部的每个值都在printf之前打印,但是在按引用传递此结构时,应用程序崩溃。

What i want to know is why i'm getting this Segmentation Fault. 我想知道的是为什么我会遇到此细分错误。 Since it appeared while calling a function i thought it is some kind of layout problem but i havn't find anything like that. 由于它是在调用函数时出现的,所以我认为这是某种布局问题,但我找不到那样的东西。

Addition : Because some people weren't able to believe me that the code i hid behind "some stuff" comments doesn't change anything i want to state this here once again . 另外 :因为有些人无法相信我,我隐藏在“一些东西”注释后面的代码不会改变任何内容,因此我想在此再次声明 This code just contains a tcp socket communication and only performs read-operations. 此代码仅包含tcp套接字通信,并且仅执行读取操作。 I also am able to reproduce the error mentioned above without this code so please don't get stuck with it. 如果没有此代码,我也可以重现上述错误,因此请不要卡在其中。 Parts does not influence the object under observation at all. 零件完全不影响观察对象。

Among other potential problems, 除其他潜在问题外,

this->m_PeerList = malloc(sizeof(char)*peerCount);

is clearly wrong. 显然是错误的。

m_PeerList is a char ** , yet you're only allocating peerCount bytes, which only works if a char * pointer is one byte on your system - not likely. m_PeerList是一个char ** ,但是您只分配peerCount字节,这仅在char *指针在系统上的一个字节中才有效-不太可能。

Replace it with something like 用类似的东西替换它

this->m_PeerList = malloc(peerCount * sizeof( *( this->m_peerList ) ) );

Note that sizeof( char ) is always one - by definition. 请注意,根据定义, sizeof( char )始终为1。

Now that you have posted an almost complete code, I was able to spot two problems next to each other: 现在您已经发布了几乎完整的代码,我能够发现彼此相邻的两个问题:

    int chat_init(Chat_t* this, unsigned int nameLen, char* name, unsigned short int bindPort, unsigned int peerCount, char** peerList)
    {
      this->m_NameLength = nameLen;

      this->m_Name = malloc(sizeof(char) * (nameLen + 1)); // correct
  //< this->m_Name = malloc(sizeof(char) * nameLen);       // wrong

      strcpy(this->m_Name, name);                          // correct
  //< memcpy(this->m_Name, name, nameLen);                 // wrong
      ...

The lines starting with //< is your original code: //<开头的行是您的原始代码:

Here you don't allocate enough space, you need to account for the NUL terminator: 在这里,您没有分配足够的空间,您需要考虑NUL终止符:

this->m_Name = malloc(sizeof(char) * nameLen);

And here you don't copy the NUL terminator: 在这里,您无需复制NUL终止符:

memcpy(this->m_Name, name, nameLen);

You really need to be aware how strings work in C. 您确实需要知道字符串在C中的工作方式。

You're not allocating enough memory for the this->m_Name . 您没有为this->m_Name分配足够的内存。 It should be on more than this if you want it to store the null-terminated string of the name. 如果您希望它存储名称的以空值结尾的字符串,则它应该在此之上。

That, or we need more information about the peerList . 那,或者我们需要有关peerList更多信息。

Why don't you debug it yourself. 您为什么不自己调试它。 If using GCC, compile your code with options -g -O0 . 如果使用GCC,请使用-g -O0选项编译代码。 Then run it with gdb : 然后使用gdb运行它:

gdb ./a.out
...
(gdb) r

If it crashes do: 如果崩溃,请执行以下操作:

(gdb) bt

This will give exactly where it crashes. 这将给出崩溃的确切位置。

Update: There may be potential problems with your code as found by other users. 更新:其他用户发现您的代码可能存在潜在问题。 However, memory allocation related issues will not crash your application just on calling function chat_communicate . 但是,与内存分配有关的问题不会仅在调用函数chat_communicate应用程序崩溃。 There could be different reasons for this behaviour ranging from stack overflow to improper compilation. 导致此行为的原因可能有多种,从堆栈溢出到编译不正确。 Without seeing the whole code it is very difficult to tell. 如果不看完整的代码,很难分辨。 Best advice is to consider review comments by other users and debug it yourself. 最好的建议是考虑其他用户的评论并自行调试。

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

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