HEAP SORT TOP DOWN - heapsort

Unhandled exception at 0x00EF140E in Homework2_FA.exe: 0xC0000005: Access violation reading location 0x006F68DC.
I dont understand why this error appears.
void build_heap_TD(int array[], int array_size)
{
for (int i = 2; i <= array_size; i++)
max_heap_insertion(array, array[i],array_size);//here appears the error
}
this is my max_heap_insertion function I want a TOP DOWN approach
void max_heap_insertion(int array[], int key, int array_size)
{
int heap_size = array_size;
array[heap_size] = array[heap_size + 1];
array[heap_size] = 999999;
heap_increase_key(array, array[heap_size], key);
}

Not much to go on here, but most likely array indexes in your (unknown) language are zero-based, so your i <= array_size condition should really be i < array_size.

Related

LZ77 slow compression speed

I'm writing simple compression program using LZ77 algorithm. My problem is very slow compression speed on any big files (for 2 MB image it takes more than 1 minute if buffer size is 12 and dictionary size is 4096). I use Boyer-Moore-Horspool algorithm for searching current buffer prefixes in the dictionary. Please, tell me what could cause such slowdown and are there any ways to improve this code's performance?
void findLongestMatch(unsigned char* d, unsigned char* b, short &len, short &off)
{
short alphabet[256];
short shift = 0;
short dict_pos=0;
bool found = false;
if(cur_dict_length==0) { return; }
for(int prefix_length=cur_buf_length-1; prefix_length>=0; prefix_length--)
{
found=false;
for(int j=0; j<256; j++)
{
alphabet[j]=prefix_length+1;
}
for(int j=prefix_length; j>=1; j--)
{
alphabet[(unsigned char)b[j]]=j;
}
shift = 0;
dict_pos = cur_dict_length-(prefix_length+1);
while(dict_pos>=0)
{
if(memcmp(&d[dict_pos], &b[0], prefix_length+1)==0)
{
found=true;
len=prefix_length+1;
off=cur_dict_length-dict_pos;
break;
}
shift = alphabet[(unsigned char)d[dict_pos]];
dict_pos = dict_pos-shift;
}
if(found==true) break;
}
return;
}
void compressData(long block_size, unsigned char* s, fstream &file_out)
{
unsigned char buf_out[3];
unsigned char* dict;
unsigned char* buf;
link myLink;
file_out.seekp(0, ios_base::beg);
cur_dict_length = 0;
cur_buf_length = buf_length;
for(int i=0; i<block_size; i++)
{
buf=&s[i];
dict=&s[i-cur_dict_length];
myLink.length=0;myLink.offset=0;
findLongestMatch(dict,buf,myLink.length,myLink.offset);
if(myLink.length<=buf_length) myLink.next=buf[myLink.length];
else myLink.next=s[i];
compactLink(myLink, buf_out);
for(int j=0; j<3; j++)
{
file_out << buf_out[j];
}
i=i+myLink.length;
if(cur_dict_length<dict_length) {
cur_dict_length=cur_dict_length+1+myLink.length;
if(cur_dict_length>dict_length) cur_dict_length=dict_length;
}
if(i+cur_buf_length>=block_size) cur_buf_length=cur_buf_length-1-(i+cur_buf_length-block_size);
}
}
As noted, it's the algorithm that is your issue. You can use a chained hash like deflate, or a suffix tree.

What is segmentation fault. How to deal with it [duplicate]

This question already has answers here:
What is a segmentation fault?
(17 answers)
Closed 2 years ago.
Problem:
A student signed up for workshops and wants to attend the maximum
number of workshops where no two workshops overlap. You must do the
following: Implement structures:
struct Workshop having the following members: The workshop's start time. The workshop's duration. The workshop's end time.
struct Available_Workshops having the following members: An integer, (the number of workshops the student signed up for). An
array of type Workshop array having size . Implement functions:
Available_Workshops* initialize (int start_time[], int duration[], int n) Creates an Available_Workshops object and
initializes its elements using the elements in the and parameters
(both are of size ). Here, and are the respective start time and
duration for the workshop. This function must return a pointer to
an Available_Workshops object.
int CalculateMaxWorkshops(Available_Workshops* ptr) Returns the maximum number of workshops the student can attend—without overlap.
The next workshop cannot be attended until the previous workshop
ends. Note: An array of unkown size ( ) should be declared as
follows: DataType* arrayName = new DataType[n];
Your initialize function must return a pointer to an
Available_Workshops object. Your CalculateMaxWorkshops function
must return maximum number of non-overlapping workshops the student
can attend.
Sample Input
6
1 3 0 5 5 8
1 1 6 2 4 1
Sample Output
4
Explanation The first line denotes , the number of workshops. The next line contains space-separated integers where the integer
is the workshop's start time. The next line contains
space-separated integers where the integer is the workshop's
duration. The student can attend the workshops and without
overlap, so CalculateMaxWorkshops returns to main (which then
prints to stdout).
MY CODE:
#include <iostream>
using namespace std;
class Workshop{
public:
int start_time{},duration{},end_time{};};
class Available_Workshops
{
public:
int n{};
struct Workshop*arr=new struct Workshop[n];
~Available_Workshops()
{
delete [] arr;
}
void arr_sort();
void arr_delete(int i);
};
////////////////////////////////////////////////////////////////////////////////////////////
Available_Workshops * initialize(int start_time[],int duration[],int n)
{
Available_Workshops * x=new Available_Workshops{};
x->n=n;
for(int i=0;i<n;i++)
{
x->arr[i].start_time=start_time[i];
x->arr[i].duration=duration[i];
x->arr[i].end_time=start_time[i]+duration[i];
}
return x;
}
///////////////////////////////////////////////////////////////////////////////////////////
void Available_Workshops:: arr_delete(int i)
{
n-=1;
for(int j=i;j<n;j++)
{
arr[j]=arr[j+1];
}
}
///////////////////////////////////////////////////////////////////////////////////////////
void Available_Workshops:: arr_sort()
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[i].start_time>arr[j].start_time)
{
struct Workshop temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CalculateMaxWorkshops(Available_Workshops * x)
{
x->arr_sort();
for(int i=0;i<x->n-1;i++)
{
for(int j=i+1;j<x->n;j++)
{
if(x->arr[i].end_time>x->arr[j].start_time)
{
if(x->arr[i].duration>=x->arr[j].duration)
x->arr_delete(i);
else x->arr_delete(j);
j--;
}
}
}
int y=x->n;
delete x;
return y;
}
int main(int argc, char *argv[]) {
int n; // number of workshops
cin >> n;
// create arrays of unknown size n
int* start_time = new int[n];
int* duration = new int[n];
for(int i=0; i < n; i++){
cin >> start_time[i];
}
for(int i = 0; i < n; i++){
cin >> duration[i];
}
Available_Workshops * ptr;
ptr = initialize(start_time,duration, n);
cout << CalculateMaxWorkshops(ptr) << endl;
return 0;
}
My code is not running. It has segmentation fault. Please help me find this error
You bug can be seen from the class declaration:
class Available_Workshops
{
public:
int n{};
struct Workshop* arr = new struct Workshop[n];
~Available_Workshops()
{
delete[] arr;
}
void arr_sort();
void arr_delete(int i);
};
Member n gets explicitly initialized to 0. Yet, your initialize function will happily fill in more elements into arr (an array of zero elements) and cause all kinds of undefined behavior.
You really, really want a proper constructor for your class instead of trying to inline initialize the members.
Available_Workshops(int size) :
n(size)
{
arr = new Workshop[n];
}
Another issue, although not related to your crash is inside your arr_delete function.
for (int j = i; j < n; j++)
{
arr[j] = arr[j + 1];
}
When j == n-1 on the last iteration of the loop, it will execute arr[n-1] = arr[n]. Accesing arr[n] is undefined behavior since the only valid indices in the array are from [0..n-1]

how i can pass array argument to C++ function

I want to pass an array from one object, store reference and then work with this array inside my function, but...
I have a terrible misunderstanding of passing an array process: In the class TreeType.
I’m facing with an error and I have tried to resolve that for 3 days, but I couldn’t.
Function:
void AddElements(TreeType& tree, int info[], int fromIndex, int toIndex)
{
int midIndex;
if (fromIndex <= toIndex)
{
midIndex = (fromIndex + toIndex) / 2;
tree.PutItem(info[midIndex]);
AddElements(tree, info, fromIndex, midIndex - 1);
// Complete the left subtree.
AddElements(tree, info, midIndex+1, toIndex);
// Complete the right subtree.
}
}
void MakeTree(TreeType& tree, int info[], int length)
// Creates a binary tree from a sorted array.
{
tree.MakeEmpty();
int arrayb[length];
for(int i = 0; i < length; i++)
{
cout << "Enter Value to make tree:" << endl;
cin >> arrayb[i];
}
AddElements(tree, info, 0, length-1);
}
And invoked in main.cpp.
else if (command == "MakeTree")
{
int length=25;
//int arrayb[length];
int arrayb[]={-1000,-967,-923,-844,-669,-567,-455,-267,-209,-183,-59,-23,68,132,159,170,222,228,233,241,389,479,824,939,985};
tree.MakeTree(tree,arrayb,length);
Error capture

bootloader avr atmega128RFA1

I am also working on the bootloader.
I had the problem in the following:
Once the cmd 'B' is received, later, 'F' is received, then I would start to call block load.
static void start_block_flash_load(uint16_t size, uint32_t *addr) {
uint16_t data_word;
uint8_t sreg = SREG;
uint16_t temp;
int i;
uint8_t my_size;
fprintf(lcdout, "B");
cli();
// Disable interrupts
(*addr) <<= 1;
if (size <= SPM_PAGESIZE) {
boot_page_erase(*addr);
boot_spm_busy_wait();
fprintf(lcdout, "%"PRIu16, size);
uint16_t i;
//store all values. PROBLEM here!!!
my_size = 208;
uint8_t buf[SPM_PAGESIZE] = { 0 };
for (i = 0; i < my_size; i++) {
//for (i=0; i<size; i++){
buf[i] = uart_getc();
// lcd_clear();
// lcd_setCursor(0, 2);
// fprintf(lcdout, "%3d", i);
// _delay_ms(500);
}
for (i = 0; i < my_size; i += 2) { //if size is odd, then use do-while
uint16_t w = buf[i];
w += buf[i + 1] << 8; //first one is low byte, second is high???
boot_page_fill((*addr)+i, w);
}
boot_page_write(*addr);
boot_spm_busy_wait();
(*addr) >>= 1;
uart_putc('\r');
} else
uart_putc('?');
boot_rww_enable ();
SREG = sreg;
}
I can see on the lcd that the size of the block is 256. However, when entering the loop to collect data, it will get stuck.
I tested with my_size and I found that only if my_size=208 the program will run further.
The strange thing is that if I put some statements inside the loop, e.g.
lcd_clear();
lcd_setCursor(0, 2);
then 'i' which I printed out on lcd will not go up to 140 something. I put different statements, the 'i' will give different value. That is very strange, since the uart_getc() will not lose data.
What I expect is that the loop will go up to 256. I cannot figure out what happened there.
Please help if you have any idea.
Thanks

Ways to parallelize this using OpenMP?

Can anybody suggest a best way to parallelize this using openmp? The program gets aborted when I run this code.
void grayerode(int **img, int height, int width, int filterheight,
int filterwidth, int iterations, int pixrange)
{
int maxlabel=0;
int fh, fw, iters, pixval=0, i, j, s, k;
int fhlimit = filterheight/2;
int fwlimit = filterwidth/2;
int **smoothedlabels;
allocate_2D_int_matrix ( &smoothedlabels, height, width );
#pragma omp parallel for shared(smoothedlabels,height,width,k)
for (i=0; i<height; i++)
for (j=0; j<width; j++)
smoothedlabels[i][j] = img[i][j];
int *labeltemp = (int *)malloc(pixrange*sizeof(int));
for (s=0; s<pixrange; s++)
labeltemp[s] = 0;
for (iters=0; iters<iterations; iters++) {
#pragma omp parallel for private(i,j,labeltemp)
for (i=fhlimit; i<height-fhlimit; i++) {
for (j=fwlimit; j<width-fwlimit; j++) {
for (fh=-fhlimit; fh<=fhlimit; fh++)
for (fw=-fwlimit; fw<=fwlimit; fw++) {
labeltemp[img[i+fh][j+fw]]++;
}
for (s=0; s<pixrange; s++) {
if (labeltemp[s]>maxlabel) {
maxlabel = labeltemp[s];
pixval = s;
}
}
smoothedlabels[i][j]=pixval;
for (s=0; s<pixrange; s++)
labeltemp[s] = 0;
maxlabel = 0;
}
}
}
for (i=0; i<height; i++)
for (j=0; j<width; j++)
img[i][j] = smoothedlabels[i][j];
free_2D_int_matrix ( &smoothedlabels );
free(labeltemp);
return;
}
A few things:
You are not declaring private variables correctly. One example of doing it the correct way in your code:
#pragma omp parallel for private(i,j) shared(smoothedlabels, img, width, height)
for(i=0; i<height; i++)
for(j=0; j<width; j++)
smoothedlabels[i][j] = img[i][j]
It is important that j remains private or each thread will try change its value - giving you unexpected behaviour. (Note: i is actually implicitly declared private when you declare the pragma statement, but I always prefer to state it explicitly for better readability)
Try avoiding 2D arrays because they restrict your ability to parallelize. In the same example you could do the following:
#pragma omp parallel for private(i) shared(width, height, smoothedlabels, img)
for(i=0; i<width * height; i++)
smoothedlabels[i] = img[i]
This will parallelize the entire loop for you rather than just the outer loop. You can order your 1D array either column wise or row wise.
Same thing goes for the rest of the loops - just apply the same concept.
Later in your code for example, you have the following:
for (fh=-fhlimit; fh<=fhlimit; fh++)
for (fw=-fwlimit; fw<=fwlimit; fw++) {
labeltemp[img[i+fh][j+fw]]++;
}
If you do not declare fh and fw private, then you will get unexpected behaviour for the same reason not declaring j before would give you unexpected behaviour.

Resources