Malloc 的客户端/服务器问题?

标签 c sockets malloc

我正在处理的这项作业的一部分涉及一个通过套接字执行来自客户端的命令的程序。现在我唯一需要编辑的文件是 mathServer.c 我目前陷入了所提供说明中的几个部分中的其中一个:

完成方法 - doServer()。 doServer() 应该有一个循环,等待客户端连接到listenFd。当客户这样做时,它应该:

  1. malloc() 为 2 个整数提供足够的内存

  2. 将来自accept()的文件描述符放入其中一个空格

  3. 将threadCount的值放入另一个空间,并递增 线程数

  4. 创建一个分离线程来处理这个新客户端。我将我的函数称为handleClient(),但您可以随意称呼您的函数。传递您的 malloc() 数组的地址。

然后循环应该返回另一个accept()。

这是我的 doServer:

void doServer (int listenFd)
{
  //  I.  Application validity check:

  //  II.  Server clients:
  pthread_t     threadId;
  pthread_attr_t    threadAttr;

  int   threadCount = 0; 

  // YOUR CODE HERE
  int *a;

  while(1) {

    //1. If Malloc was NEVER (outside or inside loop) in this program then 
    // it outputs Thread 0 recieved
    a = malloc(sizeof(int) * 2);

    accept(getServerFileDescriptor(), NULL, NULL);

    // 2.
    a[0] = getServerFileDescriptor();

    // 3.
    a[1] = threadCount++;

    // ALL 4
    pthread_attr_init(&threadAttr);
    pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
    pthread_create(&threadId, &threadAttr, handleClient, &a);

    pthread_join(threadId, NULL); 
    pthread_attr_destroy(&threadAttr);

   }

}

这是我的handleClient方法:

void* handleClient(void* vPtr) {

  // Use another pointer to cast back to int*
  // Save the file descriptor and thread number in local vars
  // free() the memory

  // I wrote these 2 lines.
  int *castMe = (int *)vPtr;
  free(vPtr);

  //  II.B.  Read command:
  char  buffer[BUFFER_LEN];
  char  command;
  int fileNum;

  int fd = castMe[0];
  int threadNum = castMe[1];

  char  text[BUFFER_LEN];
  int   shouldContinue  = 1;

  while  (shouldContinue)
  {
    text[0] = '\0';

    read(fd,buffer,BUFFER_LEN);
    printf("Thread %d received: %s\n",threadNum,buffer);
    sscanf(buffer,"%c %d \"%[^\"]\"",&command,&fileNum,text);

    //printf("Thread %d quitting.\n",threadNum);
    return(NULL);

    // YOUR CODE HERE

  }

}

我发现,每当我删除 a = malloc(sizeof(int) * 2) 以及与 malloc 相关的所有内容时,它都会输出收到的线程 0。但是,当我保留 malloc 时,输出只是空白并且不会返回任何内容。

一开始我以为是因为我没有释放内存,但是内存是从handleClient释放的,对吗?

**请注意,这不是整个程序。你在这里看到的任何方法都是教授们的工作。这两种方法是我自己的(你的代码在这里)。假设教授的代码有效:) **

非常感谢任何帮助!

最佳答案

你的一段代码

// I wrote these 2 lines.
int *castMe = (int *)vPtr;
free(vPtr);

释放castMe指向的内存,当您使用它时,您将取消引用无效内存

int fd = castMe[0];       //<----- BOOM
int threadNum = castMe[1];//<----- BOOM

undefined behavior

此外,当您编写我删除了 = malloc(sizeof(int) * 2) 时,我猜您会按原样保留 a 声明

int *a;

undefined behavior因为 a 没有指向有效的内存地址。

关于Malloc 的客户端/服务器问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42665506/

相关文章:

c - 裸机环境下类似 stdlib 的库? (内存管理和希望 pthread 支持)

c - 如何对 char 字符串/数组使用 malloc() 函数?

c - printf: 不能使用 %*c 打印少于 1 个字符

python - 是否有用 C 编写的 python 模块的 fini 例程?

c# - 使用 .NET 创建 100,000 个 tcp 连接

客户端断开连接后 C 套接字 TCP 服务器失败

c++ - 导出对象后何时释放 dll

c++ - 简单的 Linux 信号处理

c# - 一些异步套接字代码 - 帮助垃圾收集?

c - 在 C 中分配内存困惑