Can';在一个函数中不要使用malloc两次

Can';在一个函数中不要使用malloc两次,c,memory-management,malloc,C,Memory Management,Malloc,我正在尝试编写一个简单的HTTP服务器。 我编写了一个名为“handleConnection”的简单函数来处理传入连接。 我使用两个malloc函数。第一个是接收GET头,第二个是从GET头提取路径,第二个是导致malloc():损坏的顶部大小\n错误。 代码如下: int handleConnection(int sockfd) { struct sockaddr_in client; socklen_t clientLength = sizeof(struct sockadd

我正在尝试编写一个简单的HTTP服务器。 我编写了一个名为“
handleConnection
”的简单函数来处理传入连接。 我使用两个malloc函数。第一个是接收GET头,第二个是从GET头提取路径,第二个是导致
malloc():损坏的顶部大小\n错误。
代码如下:

int handleConnection(int sockfd)
{
    struct sockaddr_in client;
    socklen_t clientLength = sizeof(struct sockaddr_in);
    int new_sockfd;
    
    new_sockfd = accept(sockfd, (struct sockaddr*)&client, &clientLength);
        
    // receive get header
    int getHeaderSize = 0;
    char *getHeader = malloc(getHeaderSize);
    char tempBuffer;
    
    // stop receiving while loop when matchedTerminators is equal to 2
    int matchedTerminators = 0;
    char terminators[2] = {'\r', '\n'};
    
    // receiving while loop
    while(matchedTerminators != 2)
    {
        recv(new_sockfd, (void *)&tempBuffer, 1, 0);
                        
        if(tempBuffer == terminators[0] || tempBuffer == terminators[1])
            matchedTerminators++;           
        else
        {
            matchedTerminators = 0;
            getHeaderSize++;
            strcat(getHeader, &tempBuffer);
        }
    }
    // If already received the get header
      
    printf("%s\n", getHeader);
    
    // extract the path(/) from get header
    int pathSize = 0; // this value might increase later
    char* path = malloc(pathSize); // when pathSize is increaced this malloc function cause error
    
    /*
        Code to extract the path from get header
    */
    
    // free malloc
    free(path);
    free(getHeader);
    
    
    return 0;
}

在这里分配0字节的内存:

int getHeaderSize = 0;
char *getHeader = malloc(getHeaderSize);
在这里,您尝试在分配的0字节中存储一个字节的数据:

        strcat(getHeader, &tempBuffer);
另外:
strcat
仅对以null结尾的字符串有效,并且您从未尝试将getHeader转换为以null结尾的字符串

你可能已经知道这一点,但这是初学者的一个常见错误:除非另有说明,否则计算机按照你告诉它的顺序进行操作。它不能同时完成所有的事情。它不会回去重做它已经做过的事情(除非你告诉它)。如果执行
malloc(getHeaderSize)
并且
getHeaderSize
为0,则它分配0字节的内存。如果在此之后将
getHeaderSize
更改为100,则仍然分配了0字节的内存,因为计算机不进行时间旅行。

int-getHeaderSize=0;
char*getHeader=malloc(getHeaderSize);
// ...
int路径大小=0;
char*path=malloc(路径大小);

这两个
molloc
调用为0字节分配内存,因此当您尝试访问一些值(如
path[0]
)时,它必须超出内存范围。您将得到错误
malloc():损坏的top size
,这意味着您错误地访问了内存。

您的
malloc
调用都在分配一个零大小的内存块。在调用分配器之前,您需要确定参数大小。但是我在调用期间增加了getHeaderSize和pathSizeloops@SwamHtetAung:这对您分配的内容没有影响。这些变量和分配的内存块之间没有神奇的联系。谢谢我使用realloc,它解决了我的问题。如果没有最后一句话,这个答案会更好。