c++ - Windows 触发了 c 中的断点?

标签 c++ c

<分区>

当运行时执行到语句 free(dat) 时出现一个对话框

Windows has triggered a breakpoint in project.exe. This may be due to a corruption of the heap, which indicates a bug in project.exe or any of the DLLs it has loaded.

while(1)
{
    char *dat;

    std::cout<<"Enter command\n";
    memset(command, 0, 30);
    std::cin>>command;
    m_size = strlen(command)+2;
    printf("send data Size: %d\n",m_size);
    command[m_size-2] = '\r';
    dat = (char*)malloc(m_size);
    if(!dat)
    {
        printf("mem allocation failed");
    }
    else
    {
        memcpy(dat,command,sizeof(command));
        ok = send_data(dat);
    }
    if(ok>0)
    {
    printf("send data: %s\n",dat);

    }
    free(dat);
}

//原始代码如下所示

int main()
{
    char command[30];
    While(1)
    {....}
    return 0;
}

最佳答案

解决方案 1memcpy(dat,command,sizeof(command)); 替换为 memcpy(dat,command,m_size);

(不要覆盖分配的缓冲区)

解决方案2 或者使用 dat =(char *)malloc(sizeof(command));

(如果要写入更多,请分配更大的缓冲区)

解决方案3command[m_size-2] = '\r';之后,再添加一行

command[m_size-1] = '\0'; /* Make it NUL terminated */

并将 memcpy(dat,command,sizeof(command)); 替换为 strcpy(dat, command)

(使用 strcpy 而不是 memcpy)

解决方案4

while(1)
{
    std::string command;
    std::cout<<"Enter command\n";
    std::cin>>command;
    command += '\r';
    ok = send_data(command.c_str());
    if(ok>0)
    {
        printf("send data: %s\n",dat.c_str());
    }
}

编写 C++ 风格的代码(std::string 因为你的编译器是 C++)

关于c++ - Windows 触发了 c 中的断点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25913765/

相关文章:

c++ - 为什么在键类型中使用引用时 lambda 函数在 std::lower_bound 中不起作用?

c++ - 如何在 C++ 中将 std::string 转换为十六进制字符数组?

c++ - 这是实现支持继承的 pimpl 的有效方法吗?

c - 编写一个仅执行三个有效命令的 C 程序

c - 自定义文件打开函数在 Linux 内核中覆盖 sys_call_table 时的奇怪行为

C - 包含链表的数组

c++ - 动态数组调整大小函数问题

c# - 从 UWP c++/cx 调用 UWP C# 代码

c - GNU 编译器 KEY_F 未检测到功能键

c - fork 和线程有什么区别?