我必须询问我从这个代码中获得的中止(核心倾倒)错误
执行此代码时,我遇到了一个segfault错误。它打印了5个数字中最大的数字,并且这些数字存储在堆中。
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(5 * sizeof(int));
*ptr = 5;
*(ptr + 1) = 7;
*(ptr + 2) = 2;
*(ptr + 3) = 9;
*(ptr + 4) = 8;
int *ptr_max = (int *)malloc(sizeof(int));
*ptr_max = 0;
for (int i = 0; i < 5; i++) {
if (*ptr_max < *ptr) {
*ptr_max = *ptr;
ptr++;
} else
ptr++;
}
printf("%d\n", *ptr_max);
free(ptr);
free(ptr_max);
return 0;
}
我想知道为什么我从上面的代码中遇到了这个错误。请任何人向我解释吗?
I got a segfault error while executing this code. It prints the largest of 5 numbers, and those numbers are stored in heap-memory.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(5 * sizeof(int));
*ptr = 5;
*(ptr + 1) = 7;
*(ptr + 2) = 2;
*(ptr + 3) = 9;
*(ptr + 4) = 8;
int *ptr_max = (int *)malloc(sizeof(int));
*ptr_max = 0;
for (int i = 0; i < 5; i++) {
if (*ptr_max < *ptr) {
*ptr_max = *ptr;
ptr++;
} else
ptr++;
}
printf("%d\n", *ptr_max);
free(ptr);
free(ptr_max);
return 0;
}
I want to know why exactly I got this error from the above code. Please can anyone explain it to me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您是
free()
-ingptr
时,真正的问题就在于。一旦,您将其地址增加到指针跳到由malloc()
分配的下一个地址。始终确保*ptr
与ptr [0]
相同。因此,要解决此问题,您可以将ptr
降低5,或创建复制的指针。给出
free()
的地址的示例,它们没有指向相同的内存块:通过
5
降低的原因是这两个十六进制20
的值,与sizeof(int) * 5
。相同,或者
您可以创建指针的副本,然后对复制的操作执行操作:
然后,
free()
他们:现在,为了在大型代码库中进一步避免这些错误,请尝试使用
[]
运算符,例如:The real problem lies when you are
free()
-ing theptr
. Once, you increment a pointer its address jumps to next address allocated bymalloc()
. Always make sure that*ptr
is same asptr[0]
. So, to fix this issue, you can decrement theptr
by 5, or create a copied pointer.Example of address given to
free()
, they are not pointing to the same memory block:The reason for decrementing by
5
, is the difference between these two hexadecimal values which is20
, same assizeof(int) * 5
.OR
You can create a copy of your pointer and then perform operations on that copied one:
Then,
free()
them:Now, to avoid these mistakes further in a large code bases, try using
[]
operator like this: