c中的线程重新分配

0 c multithreading realloc

我很难重新分配一些内存来存储更大的字符串.这是在一个线程上分配内存然后将其传递给另一个线程.然后另一个线程进行一些处理并更改字符串.问题是它无法更新字符串并失败.我没有太多关于C的经验,并且肯定认为我错过了什么或者说错了什么.

这是一些示例代码.

//Struct to store options for passing across threads
typedef struct options{
    char *host;
//other options here
} options;

int main(int argc, char *argv[])
{
    //set initial options
    options *opt;
    opt->host = malloc(strlen(argv[0])*sizeof(char));
    strcpy(opt->host,argv[0]);

    //set variables for thread
    void *pData;
    DWORD dwThreadId;
    HANDLE hThread = NULL;

    //allocate memory for thread
    pData = malloc(sizeof(options));
    memcpy(pData, opt, sizeof(options));

    //create thread
    hThread = CreateThread(NULL,0,WorkerThread,pData,0,&dwThreadId);
    if (hThread ==NULL) //thread not started
         exit(1);

    //wait for thread
    WaitForSingleObject(hThread,   //Address of thread
                    INFINITE); //Timeout value

    //close thread and free memory
    CloseHandle(hThread);
    if (pData != NULL){
        //not sure why I did it this way
        HeapFree(GetProcessHeap(), 0, pData);
        pData = NULL;
    }
    if (opt != NULL){
        free(opt);
    }
    return 0;
}

//Our worker thread to change the string
DWORD WINAPI WorkerThread(void *pOpt)
{
    //get passed parameters
    options *opt = (options*) malloc(sizeof(options));
    memcpy(opt,pOpt,sizeof(options));

    //change the text of passed option
    char text[10] = "Some text";
    opt->host = (char*)realloc(opt->host,sizeof(text)*sizeof(char));
    //code crashes on line above
    strncpy(opt->host,text,sizeof(text));
}
Run Code Online (Sandbox Code Playgroud)

任何帮助非常感谢.

unw*_*ind 6

这会触发两次未定义的行为:

    options *opt;
    opt->host = malloc(strlen(argv[0])*sizeof(char));
    strcpy(opt->host,argv[0]);
Run Code Online (Sandbox Code Playgroud)

第二行是UB,因为opt未初始化,因此您无法分配opt->host.

然后你错误地计算了字符串所需的存储空间,因为没有为终结符添加1,所以该strcpy()行通过写出界限再次导致UB.

通过执行以下操作来修复分配:

opt = malloc(sizeof *opt);
opt->host = malloc(strlen(argv[0]) + 1);
Run Code Online (Sandbox Code Playgroud)

没有必要缩放sizeof(char),总是1.

这也是在线程函数中:

//get passed parameters
options *opt = (options*) malloc(sizeof(options));
memcpy(opt,pOpt,sizeof(options));
Run Code Online (Sandbox Code Playgroud)

可能只是

options opt = *pOpt;
Run Code Online (Sandbox Code Playgroud)

无需动态分配,也不需要任何memcpy()结构,它们是值,可以分配.

realloc()如果另一个线程在同一时间做同样的事情,我认为会有麻烦,请注意不要与之竞争.