Jos*_*hua 1 c heap-corruption visual-studio-2019
我尝试寻找这个问题,但找不到任何答案。我编写了一个程序,用链表实现堆栈及其操作。该程序在 C Web IDE 上编译并完美运行。
当我在 Visual Studio 中运行该程序时,它失败并给出以下错误:
调试错误!程序:C:\Users...我的文件路径检测到堆损坏:在 0x011058C8 处的正常块(#78)之后。CRT 检测到应用程序在堆缓冲区末尾后写入内存。
由于我的代码在其他地方运行良好,这一定是我使用 Visual Studio 的方式存在问题。有任何想法吗?我是 Visual Studio 的新手,恐怕这可能是愚蠢的事情,但我似乎无法弄清楚。
我在下面包含了我的代码,请注意,失败是由 Visual Studio 中的 pop() 函数引起的。
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL; //initialize head
void push(int x);
void push(int x) {
struct Node* add = (struct Node*)malloc(sizeof(struct Node*));
add->data = x;
add->next = top; //make add point to what top (head) points to (old 1st)
top = add; //make top point to add (new 1st)
}
void pop();
void pop() {
if (top == NULL) return;
struct Node* temp = top;
top = top->next;
free(temp);
}
int topp();
int topp() {
return top->data;
}
int exist();
int exist() {
if (top->next) {
return 1;
}
else {
return 0;
}
}
void PrintIt();
void PrintIt() {
struct Node* temp = top;
while (temp!= NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
push(1); PrintIt();
push(44); PrintIt();
push(23); PrintIt();
pop(); PrintIt();
push(9); PrintIt();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果您正在做一些未定义的行为(动态内存分配是这些问题的真正温床),则可能发生的未定义的事情之一是它会正常工作。
这绝不表明您正在做正确的事情,UB 是应该避免的事情,因为它可能在另一个系统、另一个编译器甚至下周二下午 3:05 上有不同的行为:-)
A couple of things I will mention:
exist() function is likely to crash for an empty list since it dereferences top. If your intent is to detect a non-empty list, you can just use return (top != NULL);.malloc in C, it can cause certain subtle errors.And, in fact, while looking at that last bullet point, there's your error (not specifically to do with casting, just that it's on that particular line):
struct Node* add = (struct Node*)malloc(sizeof(struct Node*));
// ^
// oops!
Run Code Online (Sandbox Code Playgroud)
The size of struct Node* is the size of a pointer to your structure, commonly (but not necessarily) four or eight octets. Given your actual structure has an integer and a pointer, that size is not going to be big enough.
It may work on some systems that provide a minimum dynamic memory allocation but it's definitely not advised. You should be doing:
struct Node *add = malloc(sizeof(struct Node));
// ^^^^^^^^^^^
// size of the node, not pointer
Run Code Online (Sandbox Code Playgroud)
That line has both the cast removed, and the correct size.
| 归档时间: |
|
| 查看次数: |
2093 次 |
| 最近记录: |