Debug error heap corruption detected after normal block

пару дней назад начал изучать с++ и столкнулся с такой проблемой. Цель - написать программу по вводу чисел и подсчету их среднего значения. Организовал динамический массив под это дело и в него зап...

Динамический массив в языке C++ имеет два значения: массив переменного размера(т.е. способным к добавлению и удалению в нём элементов) и массив, который мы разместили в куче(heap). В данном случае вы используете второй вид динамического массива, который сам по себе не меняет своих размеров.

Когда мы хотим считать и записать элементы массива, то у нас стоит выбор какой использовать: статический или динамический(1 или 2). Если количество элементов фиксировано(т.е. мы изначально знаем), то под это отлично подойдёт обычный статический массив, а если же количество элементов вводится с клавиатуры, то мы используем динамический, т.к. по стандарту в языке C++ количество элементов в статическом массиве должно быть известно в момент компиляции, никак не исполнения.
В вашем случае, как я понял, количество элементов фиксировано и равно 10. Тогда и вовсе динамический массив никак не обязателен.

Распишу решение в 3-х видах: с использованием статического и динамического 1-го и 2-го вида.

Статический(неспособный к растягиванию массив, выделенный в stack):

int main()
{
    constexpr int ARR_SIZE = 10;
     arr[ARR_SIZE];
    for(int i = 0; i < ARR_SIZE; ++i)
        std::cin >> arr[i];

    //обрабатываем элементы массива
    ...
    return 0;
}

Динамический(неспособный к растягиванию массив в heap):

#include <iostream>
#include <vector>

int main()
{
    int numbersInArray;
    std::cout << "Enter number of elements: ";
    std::cin >> numbersInArray;
    double *arr = new double[numbersInArray];
    for(int i = 0; i < numbersInArray; ++i)
        cin >> arr[i];
    //обрабатываем элементы массива
    ...
    return 0;
}

Динамический(cпособный к растягиванию массив, внутри сам выделен в heap):

#include <iostream>
#include <vector>

int main()
{
    std::vector < double > arr;
    int numbersInArray;
    std::cout << "Enter number of elements: ";
    std::cin >> numbersInArray;
    for(int i = 0; i < numbersInArray; ++i)
    {
        double temp_variable;
        cin >> temp_variable;
        arr.push_back(temp_variable);
    }
    //обрабатываем элементы массива
    ...
    return 0;
}

pillllot07

3 / 3 / 0

Регистрация: 02.12.2010

Сообщений: 13

1

27.02.2011, 17:17. Показов 32476. Ответов 4

Метки нет (Все метки)


Собственно такую ошибку выдаёт: «HEAP CORRUPTION DETECTED: after Normal block (#220) at 0x001970B8.
CRT detected that the application wrote to memory before start of heap buffer» хотя вроде массивы созданные мной в памяти я удаляю по окончании цикла (во всяком случае я так думаю И программа после запуска один раз проделывает всё о чём прошу, а второй раз уже отказывается. Вот кусок кода с этим циклом. Вопрос собственно: почему??? И как можно следить за памятью в Visual Studio 2010? Спасибо))

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
ptr = new int [20];// выделяем в динамической памяти место под наш массив и передаём адрес указателю без амперсанта т.к. массив и представляет собой адрес первого элемента
        ptrRed = new int [20]; //массив для остатков
        t=false;
        R=1;
        cout<<"nGive me two numbers and I'll get you gsd(NOD)"<<endl; cout<< "(first number should be bigger the second one): n";
        cin>>a>>b;
        t1=a; t2=b;
        cout<<endl;
        if(a>b)
        {
            
            while(R!=0)
            {
                
                r=R; // остаток передаём переменной r на тот случай если остаток R в следующем цикле будет равен 0, а нам надо будет вывести последний ненулевой остаток
                R=a%b; // новый остаток записываем переменную R
                quotient = a/b; // частное без остатка
                if(R!=0)
                {
                a=b;
                b=R;
                cout<<setw(15)<<"Redundance "<<count++<<" :"<<setw(8)<<a<<" "<<setw(15)<<"Quotient is: "<<setw(8)<<quotient<<endl;
                ptrRed[count-2]=R; //загоняем остаток с предидущего раза
                ptr[count-2]=quotient;//загоняем в массив частное
                }
                else
                {
                    cout<<b<<" is NOD";
                    t = true;
                }
            }
            
        }
        if(t!=true)
        cout<<r<<" is NOD";
        cout<<endl;
        for(int j=2; j<count-1;j++)
        {
        cout<<ptrRed[count-j]<<"="<<ptrRed[count-(j+2)]<<"-"<<ptrRed[count-(j+1)]<<"*"<<ptr[count-j]<<endl;
        //cout<<ptrRed[count-3]<<"="<<ptrRed[count-5]<<"-"<<ptrRed[count-4]<<"*"<<ptr[count-3]<<endl;
        }
        cout<<endl;
        Mult(ptr,ptrRed);
        delete []ptr;
        delete []ptrRed;
        count = 0;
        cout<<"Do you want more? (y/n): ";
        dir=getche();
        cout<<endl;
        
        
    }while(dir != 'n');

в аттаче скриншот ошибки

Миниатюры

HEAP CORRUPTION DETECTED
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

27.02.2011, 17:17

Ответы с готовыми решениями:

Heap Corruption detected (
что не правильно? запускаю и ошибка вылетает как на предидущей картинке

template&lt;typename TT&gt;…

Heap corruption detected
Heap corruption на строке 93 при первом же выполнении цикла. Из-за чего?
#include &lt;locale.h&gt; //…

Heap corruption detected
Ошибка возникает после отработки программы
Заголовочный файл:

#pragma once
#include&lt;iostream&gt;…

Heap corruption detected
При попытке очистить память выдает &quot;Heap corruption detected&quot;. Помогите пожалуйста(
//…

4

3 / 3 / 0

Регистрация: 02.12.2010

Сообщений: 13

27.02.2011, 17:34

 [ТС]

2

Нашёл ошибку) Действительно вылез за массив) Но как же можно следить за памятью?)



1



В астрале

Эксперт С++

8048 / 4805 / 655

Регистрация: 24.06.2010

Сообщений: 10,562

27.02.2011, 18:55

3

pillllot07, Использовать std::vector, std::string, std::list (вообщем контейнеры).
Или написать свою обертку под массив с проверкой выхода за пределы



2



3 / 3 / 0

Регистрация: 02.12.2010

Сообщений: 13

27.02.2011, 19:33

 [ТС]

4

Спасибо)



0



1 / 1 / 0

Регистрация: 19.10.2017

Сообщений: 60

02.10.2018, 09:55

5

Спасибо, аналогичная ошибка была)



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

02.10.2018, 09:55

5

  • Remove From My Forums
  • Question

  • Hi,

    I wouldn’t be asking this but this problem sometimes occurs directly after the line..

    int main(int argc, char **argv[])
    {
    PWCHAR var = (PWCHAR) malloc ((sizeof(«some\string») * sizeof(WCHAR)) + sizeof(WCHAR));

    «HEAP CORRUPTION DETECTED after normal block (#60) at 0x00000000xxxxxxxx.»
    «CRT detected the application wrote to memory after the end of the heap buffer.»

    The problem never always occurs the same line and sometimes — usually — when I run through the code step by step (F10) lines are executed but the arrow jumps past lines unless I set a specific breakpoint on the line.

    Previously another error that has occurred has been a write to invalid memory. (Error — 0x00000005, ACCESS_DENIED)

    The code seems fine when compiled as 32bit (no problems have ever occurred.) but the problems certainly occur when compiled as 64bit.

    I would like to know if it is possible that code that has been compiled has somehow been corrupted and is causing this error. I ask this only because I have had the HEAP CORRUPTION error occurred directly after the first run statement.

    Thankyou, I really need the help.

Answers

  • Heap corruptions are caused by writing too much to a memory buffer, and that is never a compiler error.

    Heap corruptions only manifest the next time you try to do something with the heap itself, like allocate more memory or free a block of memory, so it wouldn’t occur after you overwrite the end of the buffer.

    As for the debugger jumping past lines, is your configuration set to release? When it optimises code, it may remove lines completely. The debugger will just not go onto those lines. If you want the best possible debug experience, make sure it is set to the
    debug configuration.

    For a simple way of causing a heap corruption, try the following code. It will always trigger on the free line.

    int wmain()
    {
    	wchar_t *mystr = (wchar_t*)malloc(24);
    
    	wcscpy(mystr, L"a longer string");
    
    	free(mystr); //will break here
    	mystr = nullptr;
    
    	return 0;
    }

    This causes a heap corruption because obviously the buffer can only store 12 characters (including the null terminator) and you copy more than that to the buffer. The obvious way to fix this is to increase the size of the buffer.

    If you want more help though, provide code. Either your actual code or a small sample that reproduces the same issue.


    This is a signature

    Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts
    is to aid in the learning process.

    Do you want Visual Studio 11 Express to be freely installable on Windows 7 and able to write regular C++ applications? Please vote for

    this.

    • Marked as answer by

      Friday, May 11, 2012 5:38 AM

    • Unmarked as answer by
      Helen Zhao
      Friday, May 11, 2012 5:39 AM
    • Marked as answer by
      Helen Zhao
      Thursday, May 17, 2012 3:25 AM

  • HEAP CORRUPTION DETECTED is usually caused by using bad pointers or indexes in some previously executed code.  I.e., not by the line of code that produces the message. Your malloc call just gives the heap checker an opportunity to check for heap damage
    caused by previous operations.

    If you have constructors of global objects they run before main(). So that would be a good place to look for trouble.

    • Marked as answer by
      Helen Zhao
      Friday, May 11, 2012 5:38 AM
    • Unmarked as answer by
      Helen Zhao
      Friday, May 11, 2012 5:39 AM
    • Marked as answer by
      Helen Zhao
      Thursday, May 17, 2012 3:25 AM

  • Hi,

    I wouldn’t be asking this but this problem sometimes occurs directly after the line..

    int main(int argc, char **argv[])

    It is probably not related to your problem but this is not a legal definition for main. Your second parameter can be char **argv or char *argv[] but not what you have posted.

    {
    PWCHAR var = (PWCHAR) malloc ((sizeof(«some\string») * sizeof(WCHAR)) + sizeof(WCHAR));

    «HEAP CORRUPTION DETECTED after normal block (#60) at 0x00000000xxxxxxxx.»
    «CRT detected the application wrote to memory after the end of the heap buffer.»

    <snip>

    Previously another error that has occurred has been a write to invalid memory. (Error — 0x00000005, ACCESS_DENIED)

    This inidcates you already have used a bad pointer.

    You need to show your actual code since it is obviouls the call to malloc is not that early.

    • Marked as answer by
      Helen Zhao
      Friday, May 11, 2012 5:38 AM
    • Unmarked as answer by
      Helen Zhao
      Friday, May 11, 2012 5:39 AM
    • Marked as answer by
      Helen Zhao
      Thursday, May 17, 2012 3:25 AM

  • You’re not helping yourself by mixing narrow string literals in your sizeof() expressions with wide string literals in your wcscpy() calls.  However, it doesn’t seem to be the underlying problem — unless your WCHAR
    is not a two byte type like wchar_t.

    You can safely replace

    PWCHAR var = (PWCHAR) malloc ((sizeof("some\string") * sizeof(WCHAR)) + sizeof(WCHAR));
    wcscpy(var, L"some\string");

    with the equivalent

    PWCHAR var = (PWCHAR) _wcsdup(L"some\string");

    Of course, you should always check for a NULL pointer from malloc() and _wcsdup().


    Answering policy: see profile.

    • Marked as answer by
      Helen Zhao
      Friday, May 11, 2012 5:38 AM
    • Unmarked as answer by
      Helen Zhao
      Friday, May 11, 2012 5:39 AM
    • Marked as answer by
      Helen Zhao
      Thursday, May 17, 2012 3:25 AM

  • I suggest you to use the _vsnwprintf
     function, where you specify the maximum number of characters to write. Also check if you use the “( )” parentheses correctly in
    malloc, and your msg is always compatible with arguments.

    • Marked as answer by
      Helen Zhao
      Friday, May 11, 2012 5:39 AM
    • Unmarked as answer by
      Helen Zhao
      Friday, May 11, 2012 5:39 AM
    • Marked as answer by
      Helen Zhao
      Thursday, May 17, 2012 3:25 AM

Немного расскажу про дебажную кучу, речь пойдет о Visual Studio 2008. В остальных версиях дебажная куча выглядит примерно так же. Про другие компиляторы не знаю.

Основная мысль — дебажная куча отличается от релизной, чтобы облегчить отладку. И, если в дебаге произойдет порча памяти, то ее можно отловить. Visual Studio выдает в таком случае окно с сообщением и пишет в Output что-то вроде


Heap corruption at address.
HEAP[MyProg.exe]: Heap block at 0AC6A400 modified at 0AC6A6EC
past requested size of 2e4

Итак, в чем состоят отличия и каким образом отлавливаются ошибки. Давайте я пример приведу, с примером удобнее.

class CBase 
{
public:
int BaseI;
int BaseJ;
};

class CDerived : public CBase
{
public:
int DerivedI;
};

int main()
{
CBase *pBase = new CBase;//(1)

pBase->BaseI = 3;
pBase->BaseJ = 4;//(2)

delete pBase;//(3)

return 0;
}

Как будет выглядеть память в точке (1). (Чтобы вывести окно с памятью, выберите Debug->Windows->Memory->Memory1).

0x00984ED8  cd cd cd cd cd cd cd cd fd fd fd fd 00 00 00 00

У меня экземпляр класса CBase расположился по адресу 0x00984ED8. Оба int’а, а это восемь байт, заполнены значением 0xCD, Clean Memory. Это значение по умолчанию.
Дальше четыре байта 0XFD, Fence Memory, она же «no mans land». Это такой заборчик, которым обрамляется свежевыделенная память. Перед адресом 0x00984ED8 стоят точно такие же четыре байта.

Точка (2).

0x00984ED8  03 00 00 00 04 00 00 00 fd fd fd fd 00 00 00 00

Мы записали значения 3 и 4 и они идут одно за другим. Младший байт идет первым, потому что я работают с little endian платформой.

Точка (3)

0x00984ED8  dd dd dd dd dd dd dd dd dd dd dd dd 00 00 00 00

Память после удаления заполняется значениями 0xDD, Dead Memory. После вызова функции HeapFree() будет заполнена значениями 0xFEEEFEEE.

Давайте теперь сымитируем багу и посмотрим как Visual Studio ее поймает. Это реальная бага, я ее упростила до синтетического примера. На самом деле кода было больше и он был размазан по нескольким функциям.


CBase *pBase = new CBase;//(1)

pBase->BaseI = 3;
pBase->BaseJ = 4;//(2)

CDerived* pDerived = static_cast<CDerived*>(pBase);

pDerived->DerivedI = 7;//(3)
delete pBase;

Итак, мы стали приводить по иерархии с помощью static_cast’а, вместо dynamic_cast’а. Что в итоге получили. В точках (1) и (2) программа выглядит все также. В точке (3) мы полезли в чужую память и затерли забор.

03 00 00 00 04 00 00 00 07 00 00 00 00 00 00 00

После попытки вызвать delete pBase мы получим сообщение об ошибке, потому что забора нет, а это означает, что мы лазили в чужую память.

HEAP CORRUPTION DETECTED: after Normal block (#68) at 0x008D4ED8.
CRT detected that the application wrote to memory after end of heap buffer.

Еще различия между дебажной и релизной кучами приводят к тому, что программа начинает себя вести по-разному в дебаге и в релизе. Простой пример — дебажная «падает», релизная нет. Очень может быть, что «падение» — это не падение вовсе, а как раз сообщение о порче памяти. Почитайте повнимательнее, что там в окне написано.
Также народ жалуется, что дебажная версия работает сильно меденнее релизной. Причиной этого в том числе может быть дебажная куча. В интернетах пишут, что можно ее в дебаге отключить то ли с помощью переменной окружения _NO_DEBUG_HEAP, то ли NO_DEBUG_HEAP, в единицу ее надо выставить. Я пробовала ее отключить, куча осталась дебажной.

Ссылки по теме:
Win32 Debug CRT Heap Internals
Inside CRT: Debug Heap Management
Memory Management and the Debug Heap (MSDN)
Приведение типов в C++

Heap corruption detected

I have

«HEAP CORRUPTION DETECTED after normal block at

CRT DETECTED that the application wrote to memory after end of heap buffer»

error Message

After I debugged I found that this error message occured at ~String() method(delete problem)
plz help me to corect this error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
this is the full code ################################   strng3.h

#ifndef _STRNG2_H_
#define _STRNG2_H_

class String
{
private:
	char *str;
	int len;
public:
	String(const char *s);
	String();
	String(const String &st);
	~String();
	int length() const {return len;}

	String & operator=(const String &st);
	String & operator=(const char *s);

	String & operator+(const String &st);
	String & operator+(const char *s);

	friend ostream & operator<<(ostream &os,const String &st);
	friend istream & operator>>(istream &is,String &st);
	friend String & operator+(const char *s,String &st);
};

#endif


################################ strng3.cpp

#include <iostream>
#include <cstring>
using namespace std;
#include "strng3.h"

String::String()
{
	len=0;
	str=new char[1];
	str[0]='';

}

String::String(const char *s)
{
	len=strlen(s);
	str=new char[len+1];
	strcpy(str,s);
}

String::String(const String &st)
{
	len=st.len;
	str=new char[len+1];
	strcpy(str,st.str);
}

String::~String()
{
	delete [] str;               // <-------------------------------------- here
}

String & String::operator =(const char *s)
{
	delete [] str;
	len=strlen(s);
	str=new char[len+1];
	strcpy(str,s);
	return *this;
}

String & String::operator =(const String &st)
{
	if(this==&st)
		return *this;
	delete [] str;
	len=st.len;
	str=new char[len+1];
	strcpy(str,st.str);
	return *this;
}

String & String::operator +(const String &st)
{
	for(int i=0;i<=st.len;i++)
		*(str+len+i)=*(st.str+i);
	len=len+st.len;
	return *this;	
}

String & String::operator +(const char *s)
{
	int slen=strlen(s);
	char * temp=new char[slen+1];
	strcpy(temp,s);
	for(int i=0;i<slen;i++)
		*(str+len+i)=*(temp+i);
	delete [] temp;
	return *this;
}

String & operator+(const char *s,String &st)
{
	String temp(s);
	st=temp+st;                    //<---------------------- here
	return st;
}


ostream & operator<<(ostream &os,const String &st)
{
	os<<st.str;
	return os;
}

istream & operator>>(istream &is,String &st)
{
	char temp[80];
	is.get(temp,80);
	if(is)
		st=temp;
	while(is && is.get()!='n')
		continue;
	return is;
	
	/*
	char temp[20];
	is>>temp;
	char * ps=new char[strlen(temp)+1];
	strcpy(ps,temp);
	strcpy(st.str,ps);
	st.len=strlen(st.str);
	delete [] ps;
	return is;
	*/
}

#############################################

#include <iostream>
using namespace std;
#include "strng3.h"

int main()
{
	String s1("and I'm learnging c++");
	String s2="your name:";
	String s3;
	cout<<s2;
	cin>>s3;
	s2="my name is "+s3;            //<--------------- here
	cout<<s2<<".n";
	s2=s2+s1;
	cout<<s2<<"n";

	return 0;
}

Last edited on

Your operator+ overloads are seriously flawed.

To elaborate a bit more:

* + operators should be const, and should not change ‘this’. If you have code that does c = a + b;, you don’t expect ‘a’ to change, however with your operators ‘a’ would change. + operators should also return an object by value, not a reference.

* Your + overload on line 97 doesn’t increase the size of the buffer to accomidate the new, longer string. Therefore you get buffer overflows / heap corruption.

* Your + overload on line 105 changes the size of the buffer, but only to make it long enough to hold the new string — it does not make it large enough to hold both the new string and the old string (ie: it’d be find for assignment, but for appending, it’s no good). So more heap corruption there.

Thank for all your help.

I found the solution.

Now it works with no heap corruption!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
String & String::operator +(const String &st)
{
	char *temp=new char[len+st.len+1];
	strcpy(temp,str);
	for(int i = 0; i <= st.len; i++)
	{
		*(temp + len + i) = *(st.str + i);
	}
	len = len + st.len;
	delete [] str;
	str=new char[len+1];
	strcpy(str,temp);
	delete [] temp;
	return *this; 

}

String operator+(const char *s,String &st)
{
	String temp(s);
	return temp+st;
}


Last edited on

Topic archived. No new replies allowed.

Код приведённый ниже вызывает некорректное завершение программы.
Если вызывать функции на прямую через if ошибки не возникает.

HEAP[MAN2_GUI.exe]: Heap block at 0000000000395A00 modified at 000000000039626C past requested size of 85c
HEAP[MAN2_GUI.exe]: Invalid address specified to RtlValidateHeap( 0000000000350000, 0000000000395A10 )

Program: …_GUI-Desktop_Qt_5_8_0_MSVC2015_64bit-DebugdebugMAN2_GUI.exe
File: minkernelcrtsucrtsrcappcrtheapdebug_heap.cpp
Line: 888

Expression: _CrtIsValidHeapPointer(block)

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

Program: …_GUI-Desktop_Qt_5_8_0_MSVC2015_64bit-DebugdebugMAN2_GUI.exe

HEAP CORRUPTION DETECTED: after Normal block (#1903) at 0x0000000000395A40.
CRT detected that the application wrote to memory after end of heap buffer.

(Press Retry to debug the application)
HEAP[MAN2_GUI.exe]: Heap block at 0000000000395A00 modified at 000000000039626C past requested size of 85c

*.h

enum COMMAND {
        PING,
        ...
        ...
        BUFFER_OVERFLOW = 0xDF,
        WRONG_COMMAND = 0xEF,
    };
signals:
    void U(int ch, float v);
    void ManChannelDetected(int ch);

private:
    void CmdPing();
    void CmdNullFunction();
    typedef void (MyProtocol::*pFunc)();
    pFunc CmdArray[0xFF];

*.cpp
конструктор

for (int i = 0; i < 0xFF; ++i) {
    CmdArray[i] = &MyProtocol::CmdNullFunction;
}
CmdArray[PING] = &MyProtocol::CmdPing;
connect(this, &QSerialPort::readyRead, this, &MyProtocol::readyRead);

Cлот, использование.

void MyProtocol::readyRead()
{
     QMutexLocker locker(&readMutex);
     ...
    (this->*CmdArray[Data[4]])();
     ...
}

«Каллбак»

void MyProtocol::CmdPing()
{
    Channels.append((uint8_t)Data[5]);
    emit ManChannelDetected((uint8_t)Data[5]);
}

Эта программа о времени пузырьковой сортировки, вставки и сортировки.

Я запустил свою программу и получил ошибку отладки,

HEAP CORRUPTION DETECTED:after Normal block(#152)at 0x006613C0 CRT Detected

чтобы приложение записывало в память после завершения буфера кучи.

Затем я удаляю последние 3 строки кода (delete [] a; delete [] b; delete [] c) в void part_1(int n) чтобы это работало. И мой профессор сказал мне: «Ваша программа должна иметь другие ошибки, эти ошибки вызывают
ошибки в операторах удаления. «и я не должен удалять последние 3 строки кода. Я не могу найти его. Пожалуйста, помогите.

// Part-1 : --------------------------- sorting algorithms

void bubbleSort(double *x, int n)
{
// Implement the sorting function using the bubble sort algorithm.
double temp;
for (int j = 0;j < n;j++) {
for (int i = 0;i < n;i++) {
if (x[i] > x[i + 1]) {
temp = x[i];
x[i + 1] = x[i];
x[i + 1] = temp;
}
}
}
}void insertionSort(double *x, int n)
{
// Implement the sorting function using the insertion sort algorithm.

for (int i = 1;i < n;i++) {
double temp = x[i];
int j = 0;
for (j = i - 1;j >= 0 && x[j]>temp;j--) {
x[j + 1] = x[j];
}
x[j + 1] = temp;
}

}int compare_1(const void *a, const void *b) {
double *X = (double *)a;
double *Y = (double *)b;
if (*X > *Y) {
return 1;
}
else if (*X < *Y)
return -1;
return 0;

}

void part_1(int n)
{
srand((unsigned)time(NULL));  // set the seed of the random number generator

double *a = new double[n];  // create 3 arrays with identical contents
double *b = new double[n];
double *c = new double[n];

for (int i = 0; i < n; i++)
a[i] = b[i] = c[i] = rand() / 10000.0;

clock_t begin, end;
double elapsedTime;

cout << "Bubble sort: sorting an array of size " << n << endl;
begin = clock();
bubbleSort(a, n);
end = clock();

elapsedTime = (double)(end - begin) / CLOCKS_PER_SEC;
cout << "Elapsed time = " << elapsedTime << " seconds" << endl << endl;

for (int i = 0; i < n - 1; i++)
if (a[i] > a[i + 1])
{
cout << "Bubble sort : Incorrect resultsnn";
break;
}

cout << "Insertion sort: sorting an array of size " << n << endl;
begin = clock();
insertionSort(b, n);
end = clock();

elapsedTime = (double)(end - begin) / CLOCKS_PER_SEC;
cout << "Elapsed time = " << elapsedTime << " seconds" << endl << endl;

for (int i = 0; i < n - 1; i++)
if (b[i] > b[i + 1])
{
cout << "Insertion sort : Incorrect resultsnn";
break;
}

cout << "Write your statements to sort array c[] using qsort()n";
cout << "qsort: sorting an array of size " << n << endl;

begin = clock();

// #### write your statements to sort array c[] using qsort().
//      Define your own compare function.
qsort(c, n, sizeof(double), compare_1);

end = clock();

elapsedTime = (double)(end - begin) / CLOCKS_PER_SEC;
cout << "Elapsed time = " << elapsedTime << " seconds" << endl << endl;

for (int i = 0; i < n - 1; i++)
if (c[i] > c[i + 1])
{
cout << "qsort : Incorrect resultsnn";
break;
}
delete[] a;
delete[] b;
delete[] c;
}
int main()
{
part_1(50000);

system("pause");
return 0;
}

-1

Решение

Эта ошибка возникает из-за повреждения памяти. Повреждение памяти произошло из-за того, что вы записали за предел массива.
Например: если есть массив из 5 целых чисел, например

int array[5];

Вы не должны делать такие вещи, как

int n=4;
array[n+1] = 10; //array out of bound memory write operation

C / C ++ не проверяет массив вне связанной операции. Это разрешает такую ​​операцию без ошибки компиляции. В результате, когда вы запускаете программу, может произойти все что угодно. Поэтому ответственность за проверку таких ошибок лежит на программисте.

Один такой экземпляр найден в вашем коде.

void bubbleSort(double *x, int n)
{
// Implement the sorting function using the bubble sort algorithm.
double temp;
for (int j = 0;j < n;j++) {
for (int i = 0;i < n;i++) {
if (x[i] > x[i + 1]) {
temp = x[i];
x[i + 1] = x[i]; // out of bound write when i=n-1.
x[i + 1] = temp;
}
}
}
}

0

Другие решения

В bubbleSort Ваш индекс массива выходит за пределы диапазона. Измените функцию, как показано ниже, и вы увидите, что происходит:

void bubbleSort(double *x, int n)
{
// Implement the sorting function using the bubble sort algorithm.
double temp;
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
if (i + 1 >= n)
{ // index is out of range
cout << "Bummern";
exit(1);
}
if (x[i] > x[i + 1]) {
temp = x[i];
x[i + 1] = x[i];
x[i + 1] = temp;
}
}
}
}

Там, скорее всего, аналогичные проблемы в других ваших функций сортировки.

0

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Debug console mod error pattern mismatch 0 1 h ведьмак 3 что делать
  • Debug assertion failed visual c как исправить line 904
  • Debug assertion failed visual c как исправить gta sa
  • Debootstrap error release file signed by unknown key
  • Debian проверка диска на ошибки

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии