gpt4 book ai didi

c++ - 使用动态分配的变量和 _chdir windows 函数时堆损坏

转载 作者:行者123 更新时间:2023-11-30 16:42:00 27 4
gpt4 key购买 nike

在使用这些函数时,我遇到了错误。调试器在 _chdir(dirCorrente); 行上显示“damged heap”。

主要调用这些函数如下: - char* temp = getCartellaCorrente(); - 一些与这些功能无关的其他东西...... - temp = setCartellaCorrente("cd 测试")

当执行停止时,setCartellaCorrente 的 dirCorrente 值为 '"C:\Users\Luca\Desktop\remote-control-project\FirstService\Debug\test"'

我认为我在动态分配变量方面做错了。

我已经处理这个问题 48 小时了,我在互联网上搜索过,但一无所获。我想我不知道有关分配变量或 _chdir 函数的重要信息。

如果您能向我解释我所想念的内容,我将非常感激。

char* getCartellaCorrente() {
char* temp;
size_t size;
LPWSTR dirCorrente = new TCHAR[DEFAULT_BUFLEN];
GetCurrentDirectory(DEFAULT_BUFLEN, dirCorrente);
size = wcslen(dirCorrente);
temp = (char *)malloc(size);
wcstombs_s(NULL, temp, size+1, dirCorrente, size);
return temp;
}

char* setCartellaCorrente(char* relative) {
char *dirCorrente;

if (strlen(relative)>=5 && relative[4] == ':') {
dirCorrente = (char *)malloc(DEFAULT_BUFLEN);
strcpy_s(dirCorrente, DEFAULT_BUFLEN, &relative[3]);
}
else {
dirCorrente = getCartellaCorrente();
relative[2] = '\\';
strcat_s(dirCorrente, DEFAULT_BUFLEN, &relative[2]);
printf("goode %s \n", dirCorrente);
}
//fixPathSlash(dirCorrente);
printf("\n2: %s\n", dirCorrente);
int i = _chdir(dirCorrente); //HERE IT STOPS
printf("wtf: %d\n", i);
free(dirCorrente);
printf("boh\n");
return getCartellaCorrente();
}

这是我的第一个问题。抱歉,如果我错过了一些重要信息,我会快速编辑。

最佳答案

好吧,我设法解决了这个问题,因为我认为问题出在分配上。因为我现在需要快速解决这个问题,所以我使用了上面列出的方法,无论如何我将研究如何使用分配的变量并修改它以改进它。

void getCartellaCorrente(char* temp) {
size_t size;
LPWSTR dirCorrente = new TCHAR[DEFAULT_BUFLEN];
GetCurrentDirectory(DEFAULT_BUFLEN, dirCorrente);
size = wcslen(dirCorrente);
wcstombs_s(NULL, temp, DEFAULT_BUFLEN, dirCorrente, size);
}

void setCartellaCorrente(char* relative, char* dirCorrente) {

if (strlen(relative)>=5 && relative[4] == ':') {
strcpy_s(dirCorrente, DEFAULT_BUFLEN, &relative[3]);
}
else {
getCartellaCorrente(dirCorrente);
relative[2] = '\\';
strcat_s(dirCorrente, DEFAULT_BUFLEN, &relative[2]);
}
int i = _chdir(dirCorrente);
return getCartellaCorrente(dirCorrente);
}

路径变量现在以静态大小分配到 main 中,函数不会返回正确的值,而是直接更改它。

关于c++ - 使用动态分配的变量和 _chdir windows 函数时堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46072952/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com