以下是将已排序的数组转换为BST的程序。我能够使用在线C编译器编译和执行程序。当我在本地系统上尝试编译时,它会抛出一个分段错误。
SortedArraytoBST.c
#include <stdio.h>
#include <stdlib.h>
// Structure of the node
struct TNode
{
int data;
struct TNode* left;
struct TNode* right;
};
struct TNode* newNode(int data);
// Function that converts array to BST
struct TNode* SortedArrayToBST(int arr[], int start, int end)
{
if(start > end)
{
return NULL;
}
if(start == end)
{
struct TNode* newnode2 = newNode(arr[start]);
return newnode2;
}
int mid = (start+end)/2;
struct TNode* newnode = newNode(arr[mid]);
newnode->left = SortedArrayToBST(arr, start, mid-1);
newnode->right = SortedArrayToBST(arr, mid+1, end);
return newnode;
}
//NewNode Creation
struct TNode* newNode(int data)
{
struct TNode* node = (struct TNode*)malloc(sizeof(struct TNode*));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// Print the tree in preorder
void preorder(struct TNode* node)
{
if( node == NULL) return;
printf("%d\n", node->data);
preorder(node->left);
preorder(node->right);
}
// Array to BST
int main()
{
int arr[]={1,2,3};
int size = sizeof(arr)/sizeof(arr[0]);
struct TNode* root = SortedArrayToBST(arr, 0, size-1);
preorder(root);
return 0;
}
$ gcc -o SortedArraytoBST SortedArraytoBST.c
$ gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin15.2.0
Thread model: posix
$
2
-398445936
Segmentation fault: 11
2
1
3
答案 0 :(得分:1)
第36行,您的分配错误导致堆缓冲区溢出。
你应该写:
struct TNode* node = (struct TNode*)malloc(sizeof(struct TNode));
代替:
struct TNode* node = (struct TNode*)malloc(sizeof(struct TNode*));
如何调试
如果您获得gcc 4.8或更高版本,则可以运行地址清理程序:
gcc -fsanitize=address -fno-omit-frame-pointer -g myprogram.c -o myprogram
我得到了什么:
=================================================================
==22711==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000eff8 at pc 0x000000400bbb bp 0x7ffea7e3c630 sp 0x7ffea7e3c628
WRITE of size 8 at 0x60200000eff8 thread T0
#0 0x400bba in newNode /home/jyvet/TMP/myprogram.c:38
#1 0x400aac in SortedArrayToBST /home/jyvet/TMP/myprogram.c:27
#2 0x400d75 in main /home/jyvet/TMP/myprogram.c:57
#3 0x7f68db2c7b44 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b44)
#4 0x4008e8 (/home/jyvet/TMP/myprogram+0x4008e8)
0x60200000eff8 is located 0 bytes to the right of 8-byte region [0x60200000eff0,0x60200000eff8)
allocated by thread T0 here:
#0 0x7f68db6e337a in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.2+0x9437a)
#1 0x400b59 in newNode /home/jyvet/TMP/myprogram.c:36
#2 0x400aac in SortedArrayToBST /home/jyvet/TMP/myprogram.c:27
#3 0x400d75 in main /home/jyvet/TMP/myprogram.c:57
#4 0x7f68db2c7b44 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b44)
SUMMARY: AddressSanitizer: heap-buffer-overflow /home/jyvet/TMP/myprogram.c:38 newNode