c++ - 线程堆栈错误

标签 c++ c windows winapi

我的代码有问题,但无法解决。我有三个线程,线程 1 接受两个十六进制数字的输入,线程 2 和 3 将前两位数字与后两位数字交换并打印结果。

错误消息:

Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted.

DWORD WINAPI changevalue( LPVOID lpParam )
{
    WaitForSingleObject(inThread,INFINITE); //Input thread
    printf("thread 1 and 2 running \n");

    int num = 0;
    num = (int)lpParam;
    int i = 0;

    char str[10] ={0};
    char a,b;
    _itoa(num,str,16);

    while (str[i] != NULL)
    {
        i++; //Get location of last char..
    }
    //Exchange first two digits with last two.
    a = str[0];
    b = str[1];

    str[0] = str[i-2];
    str[1] = str[i-1];
    str[i-2] = a;
    str[i-1] = b;
    printf("num=%s\n",str);
    //long numl=strtol(str,&stop,16);
    //printf("num = %x\n", numl);
    //We can also take input to a string then manuplate it, and 
    //then print it in form of a string only.
    //But int is used since it is mentioned in the statement.
    printf("thread 1 and 2 exit......\n ");
    return TRUE;
}

最佳答案

如果lParam0,调用_itoa(num, str, 16)将得到单字符字符串"0”

在这种情况下,i 将是 1,并且 str[i - 2] = a 将写在之前 字符串,从而破坏堆栈。

更一般地说,lParam 的值范围从 015(含)都会触发问题。

关于c++ - 线程堆栈错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6882676/

相关文章:

c++ - 在 C++ 中,如何从字符串(或字符数组)中提取子字符串并将其写入字符串而不收到警告?

c - 使用 C 中的 fscanf 读取十六进制值序列(一次 2 个)

c - 从 unsigned int[2] 加倍?

python - ipython:暂时转到 shell,稍后返回当前 ipython session

c++ - TBB 具有更多派生任务的递归链式 react

c++ - 定义前向输出迭代器的规范方式

c++ - 提高几何形状的分辨率

c - 从 ASM 返回一个 int*

java - 使用java.exe时出错

c++ - Windows 上的文件处理例程