Printf使程序卡住而没有响应

问题描述 投票:-1回答:1

此代码获取并打印所有窗口标题和hwnd。但是,这行代码存在问题:

printf("----%s\n",hwndTitlePtrCollection[idx-1]);

如果删除此行,则应用程序运行正常,否则卡住。

#include <stdio.h>
#include <stdlib.h>
#define WINVER 0x0600
#define _WIN32_IE 0x0500
#include <windows.h>
#include <stdint.h>
uint64_t* hwndCollection;
char**    hwndTitlePtrCollection;
uint64_t  idx;
BOOL CALLBACK WindowFoundCB(HWND hwnd, char* param) {
    char *strIn2 = (char*) param;
    char *strIte;
    GetWindowText(hwnd, strIte, 256);
    if (IsWindowVisible(hwnd)){
       idx++;

       hwndCollection = (uint64_t *)realloc(hwndCollection,idx*sizeof(uint64_t));
       hwndCollection[idx-1] =  hwnd;
       printf("**** get a window's number ****\n");
       printf("----%d----%d\n",hwnd,hwndCollection[idx-1]);

       hwndTitlePtrCollection = (char**)realloc(hwndTitlePtrCollection,idx*sizeof(char*));
       hwndTitlePtrCollection[idx-1] = strIte;
       printf("**** get a window's Title ****\n");
       // this line if delete, runs OK. If exist, got stuck here
       printf("----%s\n",hwndTitlePtrCollection[idx-1]);
    }
    return TRUE;
}
int main()
{
    printf("Hello world!\n");
    idx = 0;
    char* aStr = "good";
    hwndCollection = (uint64_t*)malloc(sizeof(uint64_t)*1);
    hwndTitlePtrCollection = (char**)malloc(sizeof(char*)*1);
    EnumWindows(WindowFoundCB,&aStr);
    printf("total query recorded is: %d\n",idx);
    return 0;
}
printf
1个回答
0
投票

我很惊讶代码到达了您提到的那一行-也许只是运气-因为您在其他地方有一些重大错误。这些将导致undefined behaviour。请参阅下面的代码中的注释和修复:

BOOL CALLBACK WindowFoundCB(HWND hwnd, char* param) {
    char *strIn2 = (char*) param;
//  char *strIte; // You are not actually allocating any memory here!
    char strIte[256]; // This way, you have allocated 256 bytes for the Window name.
    GetWindowText(hwnd, strIte, 256); // In the uncorrected version, this is UB!
    if (IsWindowVisible(hwnd)){
       idx++;

       hwndCollection = (uint64_t *)realloc(hwndCollection,idx*sizeof(uint64_t));
       hwndCollection[idx-1] =  hwnd;
       printf("**** get a window's number ****\n");
       printf("----%d----%d\n",hwnd,hwndCollection[idx-1]);

       hwndTitlePtrCollection = (char**)realloc(hwndTitlePtrCollection,idx*sizeof(char*));
   //  hwndTitlePtrCollection[idx-1] = strIte; // Wrong! This just copies the pointer...
       strcpy(hwndTitlePtrCollection[idx-1], strIte); // ...this copies the contents.
       printf("**** get a window's Title ****\n");
       // this line if delete, runs OK. If exist, got stuck here
       printf("----%s\n",hwndTitlePtrCollection[idx-1]);
    }
    return TRUE;
}

尝试一下(可能还会有其他错误,但让我们逐步解决)!随时要求进一步的解释和/或澄清。

© www.soinside.com 2019 - 2024. All rights reserved.