我在使用这段代码时遇到了问题。当我执行“PrepareEncryption”(在示例中)时,代码返回一个有效指针,但是当我将它传递给“EncryptBig”时,它不再有效(指向随机数)。我最好的选择是删除原始结构。那么,如果这是问题所在,我该如何保存它呢?顺便说一句,我知道存在内存泄漏。
struct filecrypt
{
FILE* bestand;
FILE* nieuwbstnd;
unsigned int positie;
unsigned int size;
unsigned int huidig;
float procentum;
};
struct filecrypt *PrepareEncryption(char* locatie)
{
struct stat file_status;
struct filecrypt origineel, *mirror;
int error;
char* nieuw;
if (stat(locatie, &file_status) != 0)
return NULL;
error = fopen_s(&origineel.bestand, locatie, "rb");
if (error != 0)
return NULL;
error = strlen(locatie)+5;
nieuw = (char*)malloc(error);
if (nieuw == NULL)
return NULL;
strcpy_s(nieuw, error-3, locatie);
strcat_s(nieuw, error, ".cpt");
error = fopen_s(&origineel.nieuwbstnd, nieuw, "wb+");
if (error != 0)
return NULL;
origineel.huidig = 0;
origineel.positie = 0;
origineel.procentum = 0.0f;
origineel.size = file_status.st_size;
mirror = &origineel;
return mirror;
}
float EncryptBig(struct filecrypt *handle)
{
int i, index = 0;
float calc;
char buf, *bytes = (char*)malloc(10485760); // 10 MB
if (bytes == NULL)
{
handle = NULL;
fcloseall();
return -1.0f;
}
for (i = handle->huidig; i < (handle->huidig+10485760); i++)
{
if (i > handle->size)
break;
fseek(handle->bestand, i, SEEK_SET);
fread_s(&buf, 1, 1, 1, handle->bestand);
__asm
{
mov eax, dword ptr [bytes]
add eax, dword ptr [index]
mov cl, byte ptr [buf]
xor cl, 18
xor cl, 75
not cl
mov byte ptr [eax], cl
mov eax, dword ptr [index]
add eax, 1
mov dword ptr [index], eax
}
}
fwrite(bytes, 1, i, handle->nieuwbstnd);
fseek(handle->nieuwbstnd, i, SEEK_SET);
handle->huidig += i;
calc = (float)handle->huidig;
calc /= (float)handle->size;
calc *= 100.0f;
if (calc == 100.0)
{
// GEHEUGEN LEK!
// MOET NOG BIJGEWERKT WORDEN!
fcloseall();
handle = NULL;
}
return calc;
}
void example(char* path)
{
float progress;
struct filecrypt* handle;
handle = PrepareEncryption(path);
do
{
progress = EncryptBig(handle);
printf_s("%f", progress);
}
while (handle != NULL);
}
最佳答案
这是因为你返回了一个指向局部变量的指针。
局部变量存储在堆栈中,当一个函数返回时,堆栈的那个区域被其他函数重用,你留下一个指针,它现在指向未使用的内存或现在被其他东西占用的内存。这是未定义的行为,有时可能会起作用,有时可能会给您“垃圾”数据,有时可能会崩溃。
关于c - 将指针移交给 C 中的另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13531933/