有人可以告诉我这个代码有什么问题吗?

Can someone please tell me what's wrong with this code?

本文关键字:什么 问题 代码 告诉我      更新时间:2023-10-16
#include <iostream>
#include <stdlib.h>
#include <string>
#include<string.h>
#include <stdio.h>
using namespace std;
void OpCode()
{
    string mnemonic;
    int hex;
    char *op;
    cout << "Entre mnemonic : ";
    cin >> mnemonic;
    char *str1 = strdup(mnemonic.c_str());
    if(strcmp(str1, "ADD") == 0)
    {
        hex = 24;
        itoa(hex,op,16);
        cout << op;
        cout << "nEqual";
    }
    else
    cout << "nFalse";
}
int main()
{
    OpCode();
    return 0;
}

它一直运行到我使用 op 变量的部分,我尝试在 main 函数中复制和粘贴它工作得很好,为什么它在 OpCode 函数中不起作用?!提前致谢

itoa写入其第二个参数指向的内存。它本身不会分配该内存。这意味着由您为其传递有效的内存指针。你不是;您从不分配任何内存。它主要靠运气而不是设计工作。

一个简单的方法是替换定义op的行char op[9];但请记住,这是本地分配的内存,因此您无法从函数中返回它。

这是带有注释的修复程序

包括

#include <stdlib.h>
#include <string>
#include<string.h>
#include <stdio.h>
using namespace std;
void OpCode()
{
    string mnemonic;
    int hex;
    char op[10];  // allocate a pointer op that points to 10 empty spaces of type char.
    cout << "Entre mnemonic : ";
    cin >> mnemonic;
    char *str1 = strdup(mnemonic.c_str());
    if(strcmp(str1, "ADD") == 0)
    {
        hex = 24;
        itoa(hex,op,16);   // convert hex to an ASCII representation and write the ASCII to the 10 empty spaces we allocated earlier.
        cout << op;
        cout << "nEqual";
    }
    else
    cout << "nFalse";
    free (str1); // free the memory that was allocated using strdup so you do not leak memory!
}
int main()
{
    OpCode();
    return 0;
}