gpt4 book ai didi

c - 访问结构对象时出现段错误

转载 作者:行者123 更新时间:2023-11-30 17:32:49 27 4
gpt4 key购买 nike

我正在尝试用C语言实现堆排序程序。整个程序一直有效,直到我尝试打印排序数组的最后一部分。当排序完成时,我无法访问结构的任何元素。请帮助我理解错误。

程序如下 //实现堆排序的程序

#include<stdio.h>
#include<stdlib.h>
struct MaxHeap
{
int size;
int* array;
};

void print_array(int arr[],int size)
{
int i;
printf("Entered print_array function\n");
for(i=0;i<size;i++)
printf("%d ",arr[i]);
printf("\n");
}

void swap(int *p, int *q)
{
int temp=*p;
*p=*q;
*q=temp;
}

void heapify(struct MaxHeap* maxheap,int x)
{
if(maxheap->array[x] < maxheap->array[(2*x + 1)] && (2*x + 1) < maxheap->size)
swap(&(maxheap->array[x]),&(maxheap->array[(2*x + 1)]));
if(maxheap->array[x] < maxheap->array[(2*x + 2)] && (2*x + 2) < maxheap->size)
swap(&(maxheap->array[x]),&(maxheap->array[(2*x + 2)]));
}

struct MaxHeap* create_maxheap(int arr[],int size)
{
struct MaxHeap* maxheap = (struct MaxHeap*)malloc(sizeof(struct MaxHeap));
maxheap->size = size;
maxheap->array =arr;
int i;
for(i=(maxheap->size-1)/2;i>=0;i--)
heapify(maxheap,i);

return maxheap;
}

void heap_sort(struct MaxHeap* maxheap)
{
int i;
while(maxheap->size>0)
{
swap(&(maxheap->array[0]),&(maxheap->array[maxheap->size]));
maxheap->size--;
// printf("maxheap->size is %d\n",maxheap->size);
heapify(maxheap,0);
}
}

void main()
{
int tmp[] = {3,1,3};
int size = 3;
struct MaxHeap* maxheap=create_maxheap(tmp,size);

printf("The MaxHeap is created with size %d\n",maxheap->size);

heap_sort(maxheap);
printf("The array after sorting is \n");
print_array(maxheap->array,size);
}

输出结果如下

The MaxHeap is created with size 3
maxheap->size is 2
maxheap->size is 1
maxheap->size is 0
The array after sorting is
Segmentation fault

最佳答案

优秀的评论告诉您如何修复您的程序

这就是可能出错的地方

main()中有几个堆栈变量。这些将或多或少连续地放置在堆栈上。其中之一是数组,其中一条评论表明代码正在尝试访问元素超出范围。

数组只有 3 个整数长,代码尝试写入第 4 个元素(即索引为 3 ),它可能最终会改变大小变量。注意我使用了“可能”而不是“将”,因为这取决于编译器选项等, 它可以是其他变量,甚至是未使用的填充空间。这个无效下次使用变量时会注意到变量的更新。

数组越界写入的问题在于问题及其影响可能在完全不相关的代码中,给调试它的人带来痛苦,并且为近三分之一的 c/c++ 程序员提供了就业机会。

我建议打印“size”的值来检验我的假设!

现在,如果尺寸确实被破坏,并且非常高,那么下一个问题是为什么至少有 3 个值没有打印在屏幕上。答案是有的printf 写入的 FILE 结构(stdout 是 FIFO*)确实缓冲,仅当内部缓冲区已满时才写入操作系统。调试这类问题,在每个 printf() 之后放一个 fflush(stdout) 。

关于c - 访问结构对象时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23991820/

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