堆在C中出现特定大小的malloc后已损坏



我试图用C编写一个非常简单的压缩器,但遇到了错误"堆已损坏";在我的代码中。我查了一下,错误似乎是因为这句话:

ptr = (char*)malloc(count * sizeof(char));

当我把大小从count改为1000时,它就起作用了,我试着调试,看看是否有什么不同,但我找不到,我知道可能有某种溢出,但我不明白为什么和什么是解决方案,而不是写一个大数字来修复

这是我现在的代码:

#include <stdio.h>
#include <stdlib.h>
errno_t err;
int count =0;
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data) {
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
};
int* frequency(char* str) {
FILE* fptr;
err = fopen_s(&fptr, str, "r");
if (err != 0)
{
printf("The file wasn't openedn");
exit(0);
}
int* ptr;
ptr = (int*)malloc(95 * sizeof(int));
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
for (int i = 0; i < 95; i++) {
*(ptr + i) = 0;
}
char ch;
int index;
while ((ch = fgetc(fptr)) != EOF) {
index = (int)ch - 32;
(*(ptr+index))++;
}
err = fclose(fptr);
if (err != 0)
{
printf("The file wasn't closedn");
exit(0);
}
for (int i = 0; i < 95; i++) {
printf("%d ", *(ptr+i));
}
return ptr;
}
void* letFrequency(int* occLet) {
for (int i = 0; i < 95; i++) // counts how many actually occur 
{
if (*(occLet+i) > 0)
{
count++;
}
}
int* ptr;
ptr = (char*)malloc(count * sizeof(char));
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
int max = 0;
int placement = 0;
for (int j = 0; j < count; j++) {
for (int i = 0; i < 95; i++) {
if (*(occLet+i) >= max)
{
max = *(occLet+i);
placement = i;
}
}
*(ptr+j) = (char)(placement + 32);
printf("%c", *(ptr +j));
*(occLet+placement) = 0;
max = 1;
}
return ptr;
}
void binaryMap(char* letFrq) {
struct node* rootzero = newNode(1);
struct node* rootone = newNode(0);
int leaveszero = 0;
int leavesone = 0;
if (count % 2 == 0) {
leavesone = count / 2;
leaveszero = count / 2;
}
else
{
leavesone = count / 2;
leaveszero = count / 2 + 1;
printf("%d", leaveszero);
}
}

int main() {
char str[70];
printf("Enter the name of the text file you want to compress: ");
scanf_s("%s", str, sizeof(str));
int* ptrFr;
char* ptrLetFr;
ptrFr = frequency(str);
ptrLetFr = letFrequency(ptrFr);
free(ptrFr);
binaryMap(ptrLetFr);
}

行;

int* ptr;
ptr = (char*)malloc( count * sizeof(char));

显然是错误的。如果您想要count整数,那么sizeof(char)将分配太小的块。我建议作为习惯

  • 不要强制转换void*-只分配它
  • 使用指向的对象sizeof,而不是显式类型
  • 不要留下不必要的悬空指针

为此:

int* ptr = malloc(count * sizeof(*ptr) ) ;

或者,如果它倾向于char*,那么:

char* ptr = malloc(count * sizeof(*ptr) ) ;

注意这个变化有多小——你不必在三个不同的地方纠正它。

最新更新