如何在C程序中正确分配内存?

时间:2023-01-13 10:49:48

I am writing a Windows program in C for a homework assignment and I am running into a problem that causes my program to crash with program.exe has stopped working. I believe that this is due to the memory not being allocated correctly.

我正在用C编写一个Windows程序来完成一项家庭作业,我遇到的问题导致我的程序崩溃,program.exe已经停止工作。我认为这是由于内存未正确分配。

The program is supposed to start multiple threads to perform a task, I have found an example on MSDN on creating threads. I have added parts of the code into my program.

程序应该启动多个线程来执行任务,我在MSDN上找到了一个创建线程的例子。我已将部分代码添加到我的程序中。

My program:

我的节目:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <Windows.h>

#define MAX_THREADS 4
#define BUFFER_SIZE 65000

DWORD WINAPI SomeFunction( LPVOID lpParam );

char fileBuffer[BUFFER_SIZE];

typedef struct MyData {
    int val1;
    int val2;
} MYDATA, *PMYDATA;

int main(int argc, char *argv[])
{
    int i = 0;
    int j = 0;
    PMYDATA pDataArray[MAX_THREADS];
    DWORD   dwThreadIdArray[MAX_THREADS];
    HANDLE  hThreadArray[MAX_THREADS]; 


        for (i; i < MAX_THREADS; i++)
        {
            pDataArray[i] = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
                    sizeof(MYDATA));

            if( pDataArray[i] == NULL )
            {
               // If the array allocation fails, the system is out of memory
               // so there is no point in trying to print an error message.
               // Just terminate execution.
                ExitProcess(2);
            }

            // Create the thread to begin execution on its own.
            hThreadArray[i] = CreateThread(NULL, 0, SomeFunction, pDataArray[i], 0, &dwThreadIdArray[i]);

            if (hThreadArray[i] == NULL)
            {
                printf("%s\n", "Error creating thread!");
                ExitProcess(3);
            }

        }

        for (j; j < MAX_THREADS; j++)
        {
            printf("%s%d\n", "j=", j);
            WaitForSingleObject(hThreadArray[j], INFINITE);
        }

        //WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);
        i = 0;
        for(i; i<MAX_THREADS; i++)
        {
            CloseHandle(hThreadArray[i]);
            if(pDataArray[i] != NULL)
            {
                HeapFree(GetProcessHeap(), 0, pDataArray[i]);
                pDataArray[i] = NULL;    // Ensure address is not reused.
            }
        }

        printf("%s\n", "DONE!");

        return 0;

}

DWORD WINAPI SomeFunction( LPVOID lpParam)
{
    PMYDATA pDataArray;
    int anotherInt;

    anotherInt = pDataArray->val1; // PROBLEM OCCURS HERE!

    printf("%s%d\n", "Printing int ", anotherInt);


    return 0;
}

The program above should be able to start multiple threads which execute SomeFunction(). I have isolated bug to this function, specifically the line anotherInt = pDataArray->val1;. pdataArray is an array of MyData defined in a struct and each element is passed into a thread.

上面的程序应该能够启动执行SomeFunction()的多个线程。我有这个函数的隔离bug,特别是行anotherInt = pDataArray-> val1;。 pdataArray是在结构中定义的MyData数组,每个元素都传递给一个线程。

Did I not allocate the memory for the array correctly? If not, how would I access the members of the struct that was passed in as the parameter to SomeFunction()? I have gone over my code a couple of times and could not find anything wrong that I know of. The example I followed on MSDN is here.

我没有正确分配阵列的内存吗?如果没有,我将如何访问作为参数传递给SomeFunction()的结构的成员?我已经多次查看我的代码,发现我所知道的任何错误。我在MSDN上遵循的示例就在这里。

1 个解决方案

#1


2  

In MyFunction, PMYDATA pDataArray; doesn't magically become equal to the pDataArray in main. It's an uninitialized pointer, and pDataArray->val1; tries to write to a random memory location.

在MyFunction中,PMYDATA pDataArray;不会神奇地变得与主要的pDataArray相等。它是一个未初始化的指针,而pDataArray-> val1;尝试写入随机存储器位置。

Hint: you also have a LPVOID lparam which you ignore.

提示:你也有一个你忽略的LPVOID lparam。

#1


2  

In MyFunction, PMYDATA pDataArray; doesn't magically become equal to the pDataArray in main. It's an uninitialized pointer, and pDataArray->val1; tries to write to a random memory location.

在MyFunction中,PMYDATA pDataArray;不会神奇地变得与主要的pDataArray相等。它是一个未初始化的指针,而pDataArray-> val1;尝试写入随机存储器位置。

Hint: you also have a LPVOID lparam which you ignore.

提示:你也有一个你忽略的LPVOID lparam。