首页 > 解决方案 > Printf 让程序卡住而没有响应

问题描述

此代码获取并打印所有窗口标题和 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;
}

标签: cprintf

解决方案


我很惊讶代码能达到你提到的那一行——也许只是运气——因为你在其他地方有一些重大错误。这些将导致未定义的行为。请参阅以下代码中的注释和修复:

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]);

        // EDIT (1a)!
        // The following line allocates pointers to strings, but no memory for the strings...
        hwndTitlePtrCollection = (char**)realloc(hwndTitlePtrCollection,idx*sizeof(char*));
        // Here, we allocate memory for the new string …
        // EDIT (1b)!
        hwndTitlePtrCollection[idx-1] = malloc(256 * 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;
}

试试这个(可能还有其他错误,但让我们继续努力)!随时要求进一步解释和/或澄清。


推荐阅读