Navigation

    蓝鲸ROS机器人论坛

    • Register
    • Login
    • Search
    • Categories
    • Tags
    • Popular
    ROS交流群
    ROS Group
    产品服务
    Product Service
    开源代码库
    Github
    官网
    Official website
    技术交流
    Technological exchanges
    激光雷达
    LIDAR
    ROS教程
    ROS Tourials
    深度学习
    Deep Learning
    机器视觉
    Computer Vision

    C++在使用C库时malloc和new导致的错误

    技术交流
    1
    1
    409
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • weijiz
      weijiz last edited by

      在用C++编程的时候对于Linux的系统相关操作,比如socket的处理。经常要调用系统的程序库。Linux系统的库主要用c编写。一般情况下C++使用起来并没有什么问题。但是也有一些需要注意的地方。

      在使用C的库时开辟内存要用malloc,一般C++程序用new。比如下面就是我遇到的一个例子

      #ifdef WIN32
              send(sockfd, request.c_str(), request.size(), 0);
      #else
              write(sockfd, request.c_str(), request.size());
      #endif
              char *buf = (char *)malloc(1024 * 1024);
              int offset = 0;
              int rc;
      #ifdef WIN32
              while ((rc = recv(sockfd, buf + offset, 1024, 0)))
      #else
              while ((rc = read(sockfd, buf + offset, 1024)))
      #endif
              {
                  offset += rc;
              }
      #ifdef WIN32
              closesocket(sockfd);
      #else
              close(sockfd);
      #endif
              buf[offset] = 0;
              std::string res = std::string(buf);
              auto find_res = res.find("\r\n\r\n");
              auto body = res.substr(res.find("\r\n\r\n") + 4, res.size());
              free(buf);
      

      这里的buf如果用 char *buf = new char[1024 * 1024]定义buf,然后用 delete[] buf去释放内存。编译时并不会有问题,但是在Linux上运行时会出segment fault错误。在Windows上运行是正常的。
      用上面的方式定义buf和回收buf就没有问题。

      1 Reply Last reply Reply Quote 0
      • First post
        Last post
      Copyright © 2015-2021 BlueWhale community