Windows has triggered a breakpoint in

I've been always working on my software C++ & Java (build with Microsoft Visual Studio 2008 & Eclipse), and I've been trying to move it from a 32-bit system to a 64-bit one. The compilation

I’ve been always working on my software C++ & Java (build with Microsoft Visual Studio 2008 & Eclipse), and I’ve been trying to move it from a 32-bit system to a 64-bit one.

The compilation phase is alright, but on execution I get an error that says:

«Windows has triggered a breakpoint in javaw.exe. This may be due to
corruption of the heap, which indicates a bug in javaw.exe or any of
the DLLs it has loaded-.
This may also be due to user pressing F12 while javaw.exe has focus.
The output window may have more diagnostic information.
[BREAK] [CONTINUE] [IGNORE]»

You can see a snapshot of the error here:

enter image description here

Have you any idea of what this error means?
What does «corruption of the heap» mean?
Have you evere had any experience with this kind of error before?

Thank you so much!

asked Apr 16, 2012 at 10:29

DavideChicco.it's user avatar

DavideChicco.itDavideChicco.it

3,24013 gold badges52 silver badges84 bronze badges

1

It is a very nice feature of the Windows heap allocator, available since Vista. It tells you that your code has a pointer bug. Well, hopefully it is your code and not the JVM that has the bug :) You’d better assume it is your code.

The actual cause ranges somewhere between mild, like trying to free memory that was already freed or allocated from another heap (not uncommon when you interop with another program), to drastically nasty, like having blown the heap to pieces earlier by overflowing a heap allocated buffer.

The diagnostic is not fine-grained enough to tell you exactly what went wrong, just that there’s something wrong. You typically chase it down with a careful code review and artificially disabling chunks of code until the error disappears. Such are the joys of explicit memory management. If the 32-bit version is clean (check it) then this can be associated with 64-bit code due to assumptions about pointer size. A 64-bit pointer doesn’t fit in an int or long, so it is going to get truncated. And using the truncated pointer value is going to trigger this assert. That’s the happy kind of problem, you’ll find the trouble code back in the Call Stack window.

Cody Gray's user avatar

Cody Gray

236k50 gold badges486 silver badges567 bronze badges

answered Apr 16, 2012 at 12:48

Hans Passant's user avatar

Hans PassantHans Passant

913k145 gold badges1670 silver badges2507 bronze badges

0

This unfortunately usually means a memory corruption. Some double freeing of memory, function that should return but doesn’t or any other type of undefined behavior.

Your best bet of solving this, unless you have a clue as to where this corruption is, is to use a memory analysis tool.

answered Apr 16, 2012 at 10:38

Luchian Grigore's user avatar

Luchian GrigoreLuchian Grigore

251k63 gold badges454 silver badges619 bronze badges

1

I got it!
Thanks to you all, I understood it was a problem of memory, and maybe of malloc()
In fact, I read here:

The bucket-sizing factor must be a multiple of 8 for 32-bit implementations and
a multiple of 16 for 64-bit implementations in order to guarantee that addresses
returned from malloc subsystem functions are properly aligned for all data types.

IBM.com:

So, I changed the malloc() sizing in the problem point. I went from:

(int**) malloc (const * sizeof(int))

to:

(int**) malloc (const * sizeof(int64_t))

And now it works!

Thanx a lot!

answered Apr 19, 2012 at 12:20

DavideChicco.it's user avatar

DavideChicco.itDavideChicco.it

3,24013 gold badges52 silver badges84 bronze badges

1

Typically that kind of errors occurs when you trying to access the memory you didn’t allocate. Check out all of your allocations (and freeing), especially pointer-to-pointer, and code that can access dinamically allocated memory. In your case size of poiners is 64bit insdead of 32bit, that should be prime cause.

answered Apr 16, 2012 at 10:41

tukaef's user avatar

2

We are facing a crash issue in our application. To debug the crash issue we have directly executed the application from code.

To trace the error we have removed the checked from «Enable
Just My Code
» options in Debugging and we have checked the «Enabled
unmanaged code debugging
» option in project properties Debug tab.

During execution it throws the error shown below:

Windows has triggered a breakpoint in Opkey_CT.exe. 

This may be due to a corruption of the heap, which indicates a bug in Opkey_CT.exe or any of the DLLs it has loaded. 

This may also be due to the user pressing F12 while Opkey_CT.exe has focus. 

The output window may have more diagnostic information.

The line of code at which this error is thrown is highlighted bold in the code given below:

 Try

                            If File.Exists(snap_path) Then

                                Dim snapreader
As New IO.StreamReader(snap_path)

                                Dim src_snap As
String = snapreader.ReadToEnd()

                                Dim arrsnap()
As String = Split(src_snap, «,»)

                                If arrsnap.Length
> 1 Then

                                   
src_snap = arrsnap(1)

                                   
arrsnap = Nothing

                                End If

                                snapreader.Close()

                                snapreader.Dispose()

                                snapreader = Nothing

                                Dim imageBytes
As Byte() = Convert.FromBase64String(src_snap)

                                Dim ms As New
MemoryStream(imageBytes, 0, imageBytes.Length)

                                ‘ Convert byte[]
to Image

                                ms.Write(imageBytes,
0, imageBytes.Length)

                                Dim
imgsnap As Image = Image.FromStream(ms, True)

                                imgsnap.Save(Images
+ «step_» + stepid.ToString + «.png»)

                                ms.Close()

                                ms.Dispose()

                                ms = Nothing

                                imgsnap.Dispose()

                                imgsnap = Nothing

                                File.Delete(snap_path)

                            End If

                        Catch ex As Exception

                            WriteErrorLog(«ConvertingSnapFromBase64()—>
» + ex.ToString)

                        End Try

What does this error means? Is there any problem within the code?

Also when we saw the output window it is throwing some exceptions like one is «A
first chance exception of type ‘System.ArgumentOutOfRangeException’ occurred in mscorlib.dll»

What does this exception means?

We also have all output window messages if that is required please let us know.

Any help will be greatly appreaciated.


Regards, Premjeet Singh

Windows has triggered a breakpoint in xxx.exe.

Hello, there. I build my codes well, while when I run the .exe.
A message box coms out:
Windows has triggered a breakpoint in spline.exe.
This may be due to a corruption of the heap, which indicates a bug in spline.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while spline.exe has focus.
The output window may have more diagnostic information.

Does anyone know how to fix it? I know it could be out of memory,but how should I change? Thank you
Here is the code.

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
//
//  spline.h
//

#ifndef _spline_h
#define _spline_h

#include "usrdef.h"

void spline(double x[], double y[], const int n, double yp1, double ypn, double y2[])
{
    int i, k;
    double p, qn, sig, un;//, *u

    vector<double> u(n-1);
    if (yp1 > 0.99e30)
        y2[1] = u[1] = 0.0;
    else{
        y2[1] = -0.5;
        u[1] = (3.0/(x[2]-x[1]))*((y[2]-y[1])/(x[2]-x[1])-yp1);
    }
    for (i=2; i<=n-1; i++) {
        sig = (x[i]-x[i-1])/(x[i+1]-x[i-1]);
        p = sig*y2[i-1]+2.0;
        y2[i] = (sig-1.0)/p;
        u[i] = (y[i+1]-y[i])/(x[i+1]-x[i])-(y[i]-y[i-1])/(x[i]-x[i-1]);
        u[i] = (6.0*u[i]/(x[i+1]-x[i-1])-sig*u[i-1])/p;
    }
    if (ypn > 0.99e30)
        qn = un =0.0;
    else{
        qn = 0.5;
        un = (3.0/(x[n]-x[n-1]))*(ypn-(y[n]-y[n-1])/(x[n]-x[n-1]));
    }
    y2[n] = (un-qn*u[n-1])/(qn*y2[n-1]+1.0);
    for (k=n-1; k>=1; k--)
        y2[k] = y2[k]*y2[k+1]+u[k];
    u.clear();
    //delete[] u;
}

void splint(double xa[], double ya[], double y2a[], int n, double x, double yy)
{
    void nrerror(char error_text[]);
    int klo, khi, k;
    double h, b, a;
    
    klo = 1;
    khi = n;
    while (khi-klo > 1) {
        k = (khi+klo) >>1;
        if (xa[k] >x) khi=k;
        else klo = k;
    }
    h = xa[khi]-xa[klo];
    if (h == 0.0) cout<<"Bad Xa input to routine splint"<<"n";
    a = (xa[khi]-x)/h;
    b = (x-xa[klo])/h;
    yy = a*ya[klo]+b*ya[khi]+((a*a*a-a)*y2a[klo]+(b*b*b-b)*y2a[khi])*(h*h)/6.0;
}


#endif 

I’d guess that you have an out of bounds problem. Note that the index of an array starts with 0. The last valid index is the number of array elements

minus one

.

Thank you coder777, considering your advices
I modified y2[1],u[1] to y2[0],u[0] in the beginning, and (i=2;i<=n-1;i++) to (i=1;i<n-1), (k=n-1;k>=1,k—) to (k=n-2;k>=0;k—). And now it comes out with another message:
A buffer overrun has occurred in xxx.exe which has corrupted the program’s internal state.
Do you know how does it come from? Thanks

There are a lot of places where you use n directly as an index (like line 33/35/49) which is out of bounds.

Instead of decreasing the index (rather inconvenient) you might increase the size of the array and leave your current calculation like they are. But still check whether you have indexes out of bounds.

Yes, coder777. I lost them ‘n’, and now I change all of it.
When I compile and run my code, I briefly see the command prompt appear on the screen before disappearing and see the following in the debugger
‘The program ‘[5116] spline.exe: Native’ has exited with code 0 (0x0).’
no idea about this error, and I can not see the result. Thank you

I put a getchar(); into the main, and now it doesn’t disappear.
The result is also coming out correctly.
Thank you very much, coder777! thumbs up

Topic archived. No new replies allowed.


сложные случаи в отладке, повреждения памяти

От: Аноним

 
Дата:  14.07.08 08:34
Оценка:

Иногда (в среднем 1 раз из 5 запусков) выдается следующее

Windows has triggered a breakpoint in my_program.exe.
This may be due to a corruption of the heap, and indicates a bug in my_program.exe or any of the DLLs it has loaded.
The output window may have more diagnostic information

программа большая и сложная, писалась многими разработчиками в течение многих лет…
вопрос: как найти причину этой ошибки? (в output никакой дополнительной информации нет, в стеке вызовов явная фигня, похоже что там еще и стек повреждается… из нашей функции вызывается системная, из системной — снова наша, чего быть не может…)
что тут можно сделать? Может, какие-нибудь мощные отладочные тулзы типа DevPartner?


Re: сложные случаи в отладке, повреждения памяти

От:

jazzer

Россия

Skype: enerjazzer
Дата:  14.07.08 08:36
Оценка:

Здравствуйте, Аноним, Вы писали:

А>вопрос: как найти причину этой ошибки?

повставлять отладочную печать при входе-выходе из каждой функции в предполагаемом месте падения.
Лог не соврет


Re[2]: сложные случаи в отладке, повреждения памяти

От:

Pasternak

 
Дата:  14.07.08 09:59
Оценка:

Здравствуйте, jazzer, Вы писали:

J>Здравствуйте, Аноним, Вы писали:


А>>вопрос: как найти причину этой ошибки?


J>повставлять отладочную печать при входе-выходе из каждой функции в предполагаемом месте падения.

J>Лог не соврет

В дополнение к этому, можно попытаться отнять ресурсы с помощью такой утилиты как consume.exe (входит в поставку в студии). Это должно привести к более регулярным падениям, иногда помогает. Хотя могут в первую очередь совершенно другие баги повылазить


Re[2]: сложные случаи в отладке, повреждения памяти

От:

K13

http://akvis.com
Дата:  14.07.08 10:39
Оценка:

А>>вопрос: как найти причину этой ошибки?

J>повставлять отладочную печать при входе-выходе из каждой функции в предполагаемом месте падения.

J>Лог не соврет

В отладочной версии почаще проверять состояние кучи. Или даже включить проверку кучи на каждый Nth вызов аллокации памяти — читать про _CrtCheckMemory(), _CrtSetDbgFlag().

В сочетании с логом помогает найти точку, в которой память уже потоптана.
навтыкав повсюду

#if defined(_DEBUG) && defined(EXTRA_MEMORY_CHECK)
  if ( !_CrtCheckMemory() )
    _CrtDbgBreak();
#endif

можно сузить область поиска.


Re: сложные случаи в отладке, повреждения памяти

От:

carpenter

Голландия

 
Дата:  14.07.08 10:48
Оценка:

+1

Здравствуйте, Аноним, Вы писали:

А> Может, какие-нибудь мощные отладочные тулзы типа DevPartner?

DevPartner c BoundsChecker — отлично помогает — даже мозг включать не надо

Весь мир — Кремль, а люди в нем — агенты


Re: сложные случаи в отладке, повреждения памяти

От:

carpenter

Голландия

 
Дата:  14.07.08 10:52
Оценка:

Здравствуйте, Аноним, Вы писали:

А>из нашей функции вызывается системная, из системной — снова наша, чего быть не может…)

очень даже может быть если через СОМ работаете … возможны и другие варианты — вызов new например вызовет сначала аллокацию — а потом ваш конструктор
а конструктор за собой еще ченить потянет … возможно и еще варианты есть ( самому было бы интересно узнать )

Весь мир — Кремль, а люди в нем — агенты


Re: сложные случаи в отладке, повреждения памяти

От:

moorgeist

 
Дата:  14.07.08 13:01
Оценка:

Умозрительно отследить логику работы программы в этом случае практически нереально. Мы в подобных ситуациях добиваемся устойчивого воспроизведения эффекта, а затем локализуем место его возникновения путем добавления отладочных логов в подозрительных и не очень местах. Процедура длительная, итеративная, но рано или поздно приводит к решению проблемы.


Re: сложные случаи в отладке, повреждения памяти

От:

Vamp

Россия

 
Дата:  14.07.08 20:10
Оценка:

Первый шаг — воспроизвести. Сидеть и тыкать кнопки, пока не получите последовательность, хотя бы в одном случае из десяти приводящую к падению. Потом — entry-exit лог во всех функциях, которые звались на этой последовательности. Иногда помогает собрать дебажную версию и потыкаться на ней — может свалиться раньше, до того, как успеет испоганить стек.

Да здравствует мыло душистое и веревка пушистая.


Re: сложные случаи в отладке, повреждения памяти

От:

Mazay

Россия

 
Дата:  17.07.08 07:29
Оценка:

Здравствуйте, Аноним, Вы писали:

А>программа большая и сложная, писалась многими разработчиками в течение многих лет…

А>вопрос: как найти причину этой ошибки? (в output никакой дополнительной информации нет, в стеке вызовов явная фигня, похоже что там еще и стек повреждается… из нашей функции вызывается системная, из системной — снова наша, чего быть не может…)
А>что тут можно сделать? Может, какие-нибудь мощные отладочные тулзы типа DevPartner?

stack_sentry from Кодт

Автор: Кодт
Дата: 29.06.05

Главное гармония …


Re: сложные случаи в отладке, повреждения памяти

От:

McQwerty

Россия

 
Дата:  30.07.08 11:27
Оценка:

А>Иногда (в среднем 1 раз из 5 запусков) выдается следующее

А>Windows has triggered a breakpoint in my_program.exe.

А>This may be due to a corruption of the heap, and indicates a bug in my_program.exe or any of the DLLs it has loaded.
А>The output window may have more diagnostic information

А>программа большая и сложная, писалась многими разработчиками в течение многих лет…

А>вопрос: как найти причину этой ошибки? (в output никакой дополнительной информации нет, в стеке вызовов явная фигня, похоже что там еще и стек повреждается… из нашей функции вызывается системная, из системной — снова наша, чего быть не может…)
А>что тут можно сделать? Может, какие-нибудь мощные отладочные тулзы типа DevPartner?

Без бутылки и BoundsCheckers’а не обойтись. И всё равно могут остаться проблемы
Совсем недавно, вот, разбирался с проблемой. Ни одно средство не видело.

Код для MSVC6, воспроизводящий проблему:

#include <windows.h>
#include <string>
#include <queue>

BOOL work = TRUE;
CRITICAL_SECTION cs;
std::queue <std::string> q;

BOOL CALLBACK ctrlC (DWORD)
{
    work = FALSE;

    return TRUE;
} // ctrlC

DWORD CALLBACK th1 (LPVOID)
{
    while (work)
    {
        std::string s ("test");

        EnterCriticalSection (& cs);
        q. push (s);
        LeaveCriticalSection (& cs);
    }

    return 0;
} // th1

DWORD CALLBACK th2 (LPVOID)
{
    while (work)
    {
        EnterCriticalSection (& cs);
        while (!q. empty ())
        {
            std::string s (q. front ());
            q. pop ();
        }
        LeaveCriticalSection (& cs);
    }

    return 0;
} // th2

int main (int /* argc */, char* /* argv */ [])
{
    SetConsoleCtrlHandler (ctrlC, TRUE);

    InitializeCriticalSection (&cs);

    DWORD dwId = 0;
    HANDLE h [2] = { 0, 0 };
    h [0] = CreateThread (NULL, 0, th1, NULL, 0, &dwId);
    h [1] = CreateThread (NULL, 0, th2, NULL, 0, &dwId);

    WaitForMultipleObjects (2, h, TRUE, INFINITE);

    CloseHandle (h [0]);
    CloseHandle (h [1]);

    DeleteCriticalSection (&cs);

    return 0;
} // main

Если какое-то средство найдёт ошибку — сообщите.


Re: сложные случаи в отладке, повреждения памяти

От: Аноним

 
Дата:  30.07.08 13:02
Оценка:

1 (1)

А>программа большая и сложная, писалась многими разработчиками в течение многих лет…
А>вопрос: как найти причину этой ошибки? (в output никакой дополнительной информации нет, в стеке вызовов явная фигня, похоже что там еще и стек повреждается… из нашей функции вызывается системная, из системной — снова наша, чего быть не может…)
А>что тут можно сделать?
Во первых предоставить windbg отладочные символы для винды и вашей проги, дабы лучше стек лицезреть.
Во вторых на тестовой системе включить всякиые чеки gflags авось вам повезет и свалитесь пораньше
В третьих вкурить структуру хипа и хелп по команде !heap в windbg

А>Может, какие-нибудь мощные отладочные тулзы типа DevPartner?

есть и такое.. Но в больших проектах его довольно сложно юзать


Re: сложные случаи в отладке, повреждения памяти

От:

minorlogic

Украина

 
Дата:  31.07.08 19:12
Оценка:

Здравствуйте, <Аноним>, Вы писали:

DevPartner рулит , используйте если получится.

из простых эвристик ,

1. просмотреть ВСЕ new/delete и заменить по возможности умными указателями .

2. посмотреть все использования указателей. по возможности менять на сцылки .

3. посмотреть все перегрузки конструктора копирования и оператора присваивания , по возможности избавится

4. все типонебезопасные конструкции типа printf менять на типобезопасные.

и т.п.

… << RSDN@Home 1.1.4 stable SR1 rev. 568>>

Ищу работу, 3D, SLAM, computer graphics/vision.


Re[2]: сложные случаи в отладке, повреждения памяти

От:

skeptik_

 
Дата:  31.07.08 20:58
Оценка:

2 (1)

Здравствуйте, McQwerty, Вы писали:

MQ>Без бутылки и BoundsCheckers’а не обойтись. И всё равно могут остаться проблемы

MQ>Совсем недавно, вот, разбирался с проблемой. Ни одно средство не видело.

MQ> EnterCriticalSection (& cs);

MQ> q. push (s);
MQ> LeaveCriticalSection (& cs);

Критическую секцию надо бы в RAII-обёртку завернуть, так как если будет брошено исключение, то секция не закроется.


Re[2]: сложные случаи в отладке, повреждения памяти

От:

skeptik_

 
Дата:  31.07.08 21:00
Оценка:

Здравствуйте, minorlogic, Вы писали:

M>Здравствуйте, <Аноним>, Вы писали:


M>DevPartner рулит , используйте если получится.


M>из простых эвристик ,


M>1. просмотреть ВСЕ new/delete и заменить по возможности умными указателями .


M>2. посмотреть все использования указателей. по возможности менять на сцылки .


M>3. посмотреть все перегрузки конструктора копирования и оператора присваивания , по возможности избавится


M>4. все типонебезопасные конструкции типа printf менять на типобезопасные.

5. Писать юнит-тесты.


Re[3]: сложные случаи в отладке, повреждения памяти

От:

McQwerty

Россия

 
Дата:  01.08.08 13:50
Оценка:

Здравствуйте, skeptik_, Вы писали:

MQ>>Без бутылки и BoundsCheckers’а не обойтись. И всё равно могут остаться проблемы

MQ>>Совсем недавно, вот, разбирался с проблемой. Ни одно средство не видело.

MQ>> EnterCriticalSection (& cs);

MQ>> q. push (s);
MQ>> LeaveCriticalSection (& cs);

_>Критическую секцию надо бы в RAII-обёртку завернуть, так как если будет брошено исключение, то секция не закроется.

Это минимальный пример, воспроизводящий проблему.
Проблем с исключениями нет — из никто тут не бросает. Там совсем в другом засада


Re[4]: сложные случаи в отладке, повреждения памяти

От:

skeptik_

 
Дата:  01.08.08 16:50
Оценка:

2 (1)

Здравствуйте, McQwerty, Вы писали:

MQ>Здравствуйте, skeptik_, Вы писали:


MQ>>>Без бутылки и BoundsCheckers’а не обойтись. И всё равно могут остаться проблемы

MQ>>>Совсем недавно, вот, разбирался с проблемой. Ни одно средство не видело.

MQ>>> EnterCriticalSection (& cs);

MQ>>> q. push (s);
MQ>>> LeaveCriticalSection (& cs);

_>>Критическую секцию надо бы в RAII-обёртку завернуть, так как если будет брошено исключение, то секция не закроется.


MQ>Это минимальный пример, воспроизводящий проблему.

MQ>Проблем с исключениями нет — из никто тут не бросает. Там совсем в другом засада

А тебя никто спрашивать и не будет, бросят и всё. Если исключения не отключены полностью, то как минимум bad_alloc может быть кинут.


Re[5]: сложные случаи в отладке, повреждения памяти

От:

Adriano

 
Дата:  03.08.08 11:48
Оценка:

Call stack можно определить с помощью макросов. Пишем их в начале и в конце каждой функции. Способ простой, но надежный

#define my_begin try {
#define my_end }catch(std::exception& ex){throw ex;}
    catch(...){cout << __FUNCTION__ << endl;throw;}
//#define my_begin
//#define my_end

или вариант с __try __except

Подождите ...

Wait...

  • Переместить
  • Удалить
  • Выделить ветку

Пока на собственное сообщение не было ответов, его можно удалить.

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
#include "graphics.h"
#include <math.h>
#define DX 20
#define DY 20
 
void ristoch(float a, float b, float *X,int m,int n, float my, float mx)
{
    int i,j;
    float tp;
    for(i=0;i<m;i++)
 
        {tp=sqrt(pow(*(X+i*m),2)+pow(*(X+i*m+1),2));
            setfillstyle(1,4);
    if (*(X+i*m)>0) {setfillstyle(1,14); printf("%ft%ftvnen",*(X+i*m),*(X+i*m+1));}
            else {if(  (  (((tp)-a)<=0.3)   &&    (((tp)-a)>=-0.3))||     ((((tp)-b)<=0.3)  &&  (((tp)-b)>=-0.3))) {setfillstyle(1,7); printf("%ft%ftnagranizen",*(X+i*m),*(X+i*m+1));}
    else {if((((tp)-a)>0.3)&&(((tp)-b)<0.3)) {setfillstyle(1,13); printf("%ft%ftvnutrin",*(X+i*m),*(X+i*m+1));}
        if((((tp)-a)<0.3)||(((tp)-b)>0.3)) {setfillstyle(1,14); printf("%ft%ftvnen",*(X+i*m),*(X+i*m+1));}
        //delay(4000);
    }}
        pieslice(*(X+i*m)*mx+getmaxx()/2,-*(X+i*m+1)*my+getmaxy()/2,0,360,5);delay(400);}
 
}
 
void formsluch(float *X,int m, int n, int a, int b)
{
    int i,j;
    for(i=0;i<m;i++)
    for(j=0;j<n;j++)
    *(X+i*m+j)=-b+(float)rand()/RAND_MAX*2*b;
    
}
void formvvod(float *X,int m, int n)
{
    int i;
    for(i=0;i<m;i++)
        scanf("%d",&X[i]);
}
void formfile(float *X, int m)
{
    int i=0,j;
    FILE *pf_in;
    pf_in=fopen("sotr.txt", "r");
    while (!feof(pf_in))
    {fscanf(pf_in, "%d",&X[i]);i++;}
    if(i<m) {for (j=i;j<m;j++)
                    X[j]=-20+rand()%40;}
}
void vuvod(float *X,int m)
{
    int i;
    for(i=0;i<m;i++)
        
        printf("%ft%fn",*(X+i*m),*(X+i*m+1));
}
void graf(float a, float c, float *my, float *mx)
{
int osx,osy,xt,yt,xvn,xvk,yvn,yvk;
float x,y,dx,min,max,b=0,i;
char s[10];
if(a<c) {max=a;a=c;c=max;}
//установка цвета фона (синий) и цвета линий (белый)
initwindow(600,600);
setbkcolor(15);
cleardevice();
setcolor(1);
a*=-1;
//нахождение наибольшего и наименьшего значений функции
max=-a;min=a;
//расчет масштабов по оси y и по оси x
   *my=(getmaxy()-2*DY)/(max-min);
   *mx=(getmaxx()-2*DX)/(2*(b-a));
//Определение координат точки пересечения осей
osy=getmaxy()/2;
osx=getmaxx()/2;
//присвоение значений для построения осей координат
xvn=DX;xvk=getmaxx()-DX;
yvn=DY;yvk=getmaxy()-DY;
setcolor(4); //установка цвета линий для построения функции (красный)
//установка стиля линий для построения функции   
setlinestyle(0,1,3);
//расчет координат начальной точки функции  
arc(osx,osy,90,270,-a**my);
arc(osx,osy,90,270,c**my);
 
/*for(i=c*my+2;i<(-a)*my-2;i++)
{arc(osx,osy,90,270,i);
}*/
 
//установка стиля линий для построения осей координат
setlinestyle(0,1,3);
//построение осей координат
line(xvn,osy,xvk,osy);
line(osx,yvn,osx,yvk);
//setcolor(8);
setfillstyle(9,8);
floodfill((-c-((-a-c)/2))**mx+getmaxx()/2,4+getmaxy()/2,4);
floodfill((-c-((-a-c)/2))**mx+getmaxx()/2,-4+getmaxy()/2,4);
 
//pieslice(-6**mx+getmaxx()/2,-(-6)**my+getmaxy()/2,0,360,5);
//установка цвета линий для построения сетки (серый) setcolor(7);
//установка стиля линий для построения сетки   
setlinestyle(1,1,1);
outtextxy(osx-2,yvn-8,"y");
outtextxy(xvk+2,osy-8,"x");
//построение сетки
dx=(2*(b-a))/10;
for(x=a; x<=-a;x+=dx)
 {
  xt=xvn+*mx*(x-a);
  line(xt,yvn,xt,yvk);
  sprintf(s,"%.1f",x);
  outtextxy(xt,osy+8,s);
 }
  float dy=(max-min)/10;
  for(y=min; y<max+dy;y+=dy)
 {
  yt=yvk-(*my*(y-min));
  line(xvn,yt,xvk,yt);
  sprintf(s,"%.1f",y);
  if(y!=0.0) outtextxy(osx+2,yt,s);
 }
}
 
int main()
{   int m,n=2,vub;
    float b,a,*X,my,mx;
printf("input b: ");
scanf("%f",&b);
printf("input a: ");
scanf("%f",&a);
graf(b,a,&my,&mx);
printf("Input kol element");
    scanf("%d",&m);
    X = (float*)malloc(n*m*sizeof(float));
    do {printf("Input var. of enter: 1 - random, 2 - from clav, 3 - file");
    scanf("%d",&vub);
    if (vub==1) formsluch(X,m,n,a,b);
    if(vub==2) formvvod(X,m,n);
    if(vub==3) formfile(X, m);}
    while(vub>3||vub<1);
    //vuvod(X,m);
    ristoch(a,b,X,m,n,my,mx);
 getch();
}

I have made a C mex file to execute a communication protocol. The C code with which I made the communication protocol run without any problem in gcc complier provided by Code Blocks for windows operating system.

*Error: Windows has triggered a breakpoint in MATLAB.exe. This may be due to a corruption of the heap, and indicates a bug in MATLAB.exe or any of the DLLs it has loaded. The output window may have more diagnostic information * *

I get above error when I tried to run with data length (MSG_LENGTH) more than 100 bits. But it run perfectly in matlab when I run it for small data length for example 15 bits

I tried to debug my program in mex file using Microsoft visual studio 2005. But every time the point of error is not fixed. In other words, I am not able to know exact reason and place due which I am getting the error.

///***********************************************************************/////

#include <string.h> /* needed for memcpy() */

#include «mex.h»

#include «matrix.h»

#include <math.h>

#include <stdio.h>

#include <stdlib.h>

#include <limits.h>

#include «C:Dokumente und EinstellungenjainshEigene DateienMATLABvdsim.h»

#undef SLOWACS

#define FASTACS

#undef NORM

#define MAXMETRIC 128

void deci2bin(int d, int size, int *b);

int bin2deci(int *b, int size);

int nxt_stat(int current_state, int input, int *memory_contents);

void init_quantizer(void);

void init_adaptive_quant(float es_ovr_n0);

int soft_quant(float channel_symbol);

int soft_metric(int data, int guess);

int quantizer_table[256];

void sdvd_try_fourth( int* decoder_output_matrix);

void sdvd_try_fourth( int* decoder_output_matrix)

{

int i, j, l, ll; /* loop variables */

long t; /* time */

int memory_contents[K]; /* input + conv. encoder sr */

int input[TWOTOTHEM][TWOTOTHEM]; /* maps current/nxt sts to input */

int output[TWOTOTHEM][2]; /* gives conv. encoder output */

int nextstate[TWOTOTHEM][2]; /* for current st, gives nxt given input */

int accum_err_metric[TWOTOTHEM][2]; /* accumulated error metrics */

int state_history[TWOTOTHEM][K * 5 + 1]; /* state history table */

int state_sequence[K * 5 + 1]; /* state sequence list */

int *channel_output_matrix; /* ptr to input matrix */

int binary_output[2]; /* vector to store binary enc output */

int branch_output[2]; /* vector to store trial enc output */

int m, n, number_of_states, depth_of_trellis, step, branch_metric,sh_ptr, sh_col, x, xx, h, hh, next_state, last_stop; /* misc variables */

long msg_length=0;

long channel_length=0;

// double es_ovr_n0 = *esovrno;

float es_ovr_n0 = 10;

#if K==3

float channel_output_vector[] = {0.974107, 1.132812, -1.738985, -0.585913, -1.022291, 1.219668, 0.118811, 1.476064, 0.838002, -0.840128, -2.582146, 1.282722, 0.945906, -1.623774, -1.595833, -1.175974, -1.368038, -1.150094, -0.681191, 0.781831, 0.832424, 2.253263, -0.562191, 1.057578, -0.719164, -0.457746, 2.903605, 0.397414, -1.129364, 0.063622, -0.544410, 1.792516, -0.934873, -1.064703};

#endif

#if K== 5

float channel_output_vector[] = {0.974107, 1.132812, -1.738985, -0.585913, -1.022291, 1.219668, 0.118811, 1.476064, 0.838002, -0.840128, -2.582146, 1.282722, 0.945906, -1.623774, -1.595833, -1.175974, -1.368038, -1.150094, -0.681191, 0.781831, 0.832424, 2.253263, -0.562191, 1.057578, -0.719164, -0.457746, 2.903605, 0.397414, -1.129364, 0.063622, -0.544410, 1.792516, -0.934873, -1.064703,-8149759.500000,-75.157600,-2.820892,-4586784.000000};

# endif

#if K== 7

float channel_output_vector[] = {0.974107, 1.132812, -1.738985, -0.585913, -1.022291, 1.219668, 0.118811, 1.476064, 0.838002, -0.840128, -2.582146, 1.282722, 0.945906, -1.623774, -1.595833, -1.175974, -1.368038, -1.150094, -0.681191, 0.781831, 0.832424, 2.253263, -0.562191, 1.057578, -0.719164, -0.457746, 2.903605, 0.397414, -1.129364, 0.063622, -0.544410, 1.792516, -0.934873, -1.064703,-8157967.500000,-83.157600,-2.820892,-4586784.000000,3.590167,-8149438.500000,276784000.000000,-8413568.000000

};

#endif

/* ************************************************************************** */

/* n is 2^1 = 2 for rate 1/2 */

n = 2;

/* m (memory length) = K — 1 */

m = K — 1;

msg_length = MSG_LEN;

channel_length = ( msg_length + m ) * 2;

/* number of states = 2^(K — 1) = 2^m for k = 1 */

number_of_states = (int) pow(2, m);

/* little degradation in performance achieved by limiting trellis depth

to K * 5—interesting to experiment with smaller values and measure

the resulting degradation. */

depth_of_trellis = K * 5; // continue mex

/* initialize data structures */

for (i = 0; i < number_of_states; i++) {

for (j = 0; j < number_of_states; j++)

input[i][j] = 0;

for (j = 0; j < n; j++) {

nextstate[i][j] = 0;

output[i][j] = 0;

}

for (j = 0; j <= depth_of_trellis; j++) {

state_history[i][j] = 0;

}

/* initial accum_error_metric[x][0] = zero */

accum_err_metric[i][0] = 0;

/* by setting accum_error_metric[x][1] to INT_MAX, we don’t need a flag */

/* so I don’t get any more questions about this: */

/* INT_MAX is simply the largest possible integer, defined in limits.h */

accum_err_metric[i][1] = INT_MAX;

}

/* generate the state transition matrix, output matrix, and input matrix

— input matrix shows how FEC encoder bits lead to next state

— next_state matrix shows next state given current state and input bit

— output matrix shows FEC encoder output bits given current presumed

encoder state and encoder input bit—this will be compared to actual

received symbols to determine metric for corresponding branch of trellis

*/

for (j = 0; j < number_of_states; j++) {

for (l = 0; l < n; l++) {

next_state = nxt_stat(j, l, memory_contents);

input[j][next_state] = l;

/* now compute the convolutional encoder output given the current

state number and the input value */

branch_output[0] = 0;

branch_output[1] = 0;

for (i = 0; i < K; i++) {

branch_output[0] ^= memory_contents[i] & g[0][i];

branch_output[1] ^= memory_contents[i] & g[1][i];

}

/* next state, given current state and input */

nextstate[j][l] = next_state;

/* output in decimal, given current state and input */

output[j][l] = bin2deci(branch_output, 2);

} /* end of l for loop */

} /* end of j for loop */

#ifdef DEBUG

printf(«nInput:»);

for (j = 0; j < number_of_states; j++) {

printf(«n»);

for (l = 0; l < number_of_states; l++)

printf(«%2d «, input[j][l]);

} /* end j for-loop */

printf(«nOutput:»);

for (j = 0; j < number_of_states; j++) {

printf(«n»);

for (l = 0; l < n; l++)

printf(«%2d «, output[j][l]);

} /* end j for-loop */

printf(«nNext State:»);

for (j = 0; j < number_of_states; j++) {

printf(«n»);

for (l = 0; l < n; l++)

printf(«%2d «, nextstate[j][l]);

} /* end j for-loop */

#endif

channel_output_matrix = malloc( channel_length * sizeof(int) );

if (channel_output_matrix == NULL) {

printf(

«nsdvd.c: Can’t allocate memory for channel_output_matrix! Aborting…»);

exit(1);

}

/* now we’re going to rearrange the channel output so it has n rows,

and n/2 columns where each row corresponds to a channel symbol for

a given bit and each column corresponds to an encoded bit */

channel_length = channel_length / n;

/* interesting to compare performance of fixed vs adaptive quantizer */

/* init_quantizer(); */

init_adaptive_quant(es_ovr_n0);

/* quantize the channel output—convert float to short integer */

/* channel_output_matrix = reshape(channel_output, n, channel_length) */

for (t = 0; t < (channel_length * n); t += n) {

for (i = 0; i < n; i++)

*(channel_output_matrix + (t / n) + (i * channel_length) ) =

soft_quant( *(channel_output_vector + (t + i) ) );

} /* end t for-loop */

/* ************************************************************************** */

/* End of setup. Start decoding of channel outputs with forward

traversal of trellis! Stop just before encoder-flushing bits. */

for (t = 0; t < channel_length — m; t++) {

if (t <= m)

/* assume starting with zeroes, so just compute paths from all-zeroes state */

step = (int)pow(2, m — t * 1);

else

step = 1;

/* we’re going to use the state history array as a circular buffer so

we don’t have to shift the whole thing left after each bit is

processed so that means we need an appropriate pointer */

/* set up the state history array pointer for this time t */

sh_ptr = (int) ( ( t + 1 )

/* repeat for each possible state */

for (j = 0; j < number_of_states; j+= step) {

/* repeat for each possible convolutional encoder output n-tuple */

for (l = 0; l < n; l++) {

branch_metric = 0;

/* compute branch metric per channel symbol, and sum for all

channel symbols in the convolutional encoder output n-tuple */

#ifdef SLOWACS

/* convert the decimal representation of the encoder output to binary */

deci2bin(output[j][l], n, binary_output);

/* compute branch metric per channel symbol, and sum for all

channel symbols in the convolutional encoder output n-tuple */

for (ll = 0; ll < n; ll++) {

branch_metric = branch_metric + soft_metric( *(channel_output_matrix +

( ll * channel_length + t )), binary_output[ll] );

} /* end of ‘ll’ for loop */

#endif

#ifdef FASTACS

/* this only works for n = 2, but it’s fast! */

/* convert the decimal representation of the encoder output to binary */

binary_output[0] = ( output[j][l] & 0x00000002 ) >> 1;

binary_output[1] = output[j][l] & 0x00000001;

/* compute branch metric per channel symbol, and sum for all

channel symbols in the convolutional encoder output n-tuple */

branch_metric = branch_metric + abs( *( channel_output_matrix +

( 0 * channel_length + t ) ) — 7 * binary_output[0] ) +

abs( *( channel_output_matrix +

( 1 * channel_length + t ) ) — 7 * binary_output[1] );

#endif

/* now choose the surviving path—the one with the smaller accumlated

error metric

if ( accum_err_metric[ nextstate[j][l] ] [1] > accum_err_metric[j][0] +

branch_metric ) {

/* save an accumulated metric value for the survivor state */

accum_err_metric[ nextstate[j][l] ] [1] = accum_err_metric[j][0] +

branch_metric;

/* update the state_history array with the state number of

the survivor */

state_history[ nextstate[j][l] ] [sh_ptr] = j;

} /* end of if-statement */

} /* end of ‘l’ for-loop */

} /* end of ‘j’ for-loop — we have now updated the trellis */

/* for all rows of accum_err_metric, move col 2 to col 1 and flag col 2 */

for (j = 0; j < number_of_states; j++) {

accum_err_metric[j][0] = accum_err_metric[j][1];

accum_err_metric[j][1] = INT_MAX;

} /* end of ‘j’ for-loop */

/* now start the traceback, if we’ve filled the trellis */

if (t >= depth_of_trellis — 1) {

/* initialize the state_sequence vector—probably unnecessary */

for (j = 0; j <= depth_of_trellis; j++)

state_sequence[j] = 0;

/* find the element of state_history with the min. accum. error metric */

/* since the outer states are reached by relatively-improbable runs

of zeroes or ones, search from the top and bottom of the trellis in */

x = INT_MAX;

for (j = 0; j < ( number_of_states / 2 ); j++) {

if ( accum_err_metric[j][0] < accum_err_metric[number_of_states — 1 — j][0] ) {

xx = accum_err_metric[j][0];

hh = j;

}

else {

xx = accum_err_metric[number_of_states — 1 — j][0];

hh = number_of_states — 1 — j;

}

if ( xx < x) {

x = xx;

h = hh;

}

} /* end ‘j’ for-loop */

#ifdef NORM

/* interesting to experiment with different numbers of bits in the

accumulated error metric—does performance decrease with fewer bits? */

/* if the smallest accum. error metric value is > MAXMETRIC, normalize the

accum. errror metrics by subtracting the value of the smallest one from

all of them (making the smallest = 0) and saturate all other metrics

at MAXMETRIC */

if (x > MAXMETRIC) {

for (j = 0; j < number_of_states; j++) {

accum_err_metric[j][0] = accum_err_metric[j][0] — x;

if (accum_err_metric[j][0] > MAXMETRIC)

accum_err_metric[j][0] = MAXMETRIC;

} /* end ‘j’ for-loop */

}

#endif

/* now pick the starting point for traceback */

state_sequence[depth_of_trellis] = h;

/* now work backwards from the end of the trellis to the oldest state

in the trellis to determine the optimal path. The purpose of this

is to determine the most likely state sequence at the encoder

based on what channel symbols we received. */

for (j = depth_of_trellis; j > 0; j—) {

sh_col = j + ( sh_ptr — depth_of_trellis );

if (sh_col < 0)

sh_col = sh_col + depth_of_trellis + 1;

state_sequence[j — 1] = state_history[ state_sequence[j] ] [sh_col];

} /* end of j for-loop */

/* now figure out what input sequence corresponds to the state sequence

in the optimal path */

*(decoder_output_matrix + t — depth_of_trellis + 1) =

input[ state_sequence[0] ] [ state_sequence[1] ];

} /* end of if-statement */

} /* end of ‘t’ for-loop */

/* ************************************************************************** */

/* now decode the encoder flushing channel-output bits */

for (t = channel_length — m; t < channel_length; t++) {

/* set up the state history array pointer for this time t */

sh_ptr = (int) ( ( t + 1 )

/* don’t need to consider states where input was a 1, so determine

what is the highest possible state number where input was 0 */

last_stop = number_of_states / (int)pow(2, t — channel_length + m);

/* repeat for each possible state */

for (j = 0; j < last_stop; j++) {

branch_metric = 0;

deci2bin(output[j][0], n, binary_output);

/* compute metric per channel bit, and sum for all channel bits

in the convolutional encoder output n-tuple */

for (ll = 0; ll < n; ll++) {

branch_metric = branch_metric + soft_metric( *(channel_output_matrix +

(ll * channel_length + t)), binary_output[ll] );

} /* end of ‘ll’ for loop */

/* now choose the surviving path—the one with the smaller total

metric

if ( (accum_err_metric[ nextstate[j][0] ][1] > accum_err_metric[j][0] +

branch_metric) /*|| flag[ nextstate[j][0] ] == 0*/) {

/* save a state metric value for the survivor state */

accum_err_metric[ nextstate[j][0] ][1] = accum_err_metric[j][0] +

branch_metric;

/* update the state_history array with the state number of

the survivor */

state_history[ nextstate[j][0] ][sh_ptr] = j;

} /* end of if-statement */

} /* end of ‘j’ for-loop */

/* for all rows of accum_err_metric, swap columns 1 and 2 */

for (j = 0; j < number_of_states; j++) {

accum_err_metric[j][0] = accum_err_metric[j][1];

accum_err_metric[j][1] = INT_MAX;

} /* end of ‘j’ for-loop */

/* now start the traceback, if i >= depth_of_trellis — 1*/

if (t >= depth_of_trellis — 1) {

/* initialize the state_sequence vector */

for (j = 0; j <= depth_of_trellis; j++) state_sequence[j] = 0;

/* find the state_history element with the minimum accum. error metric */

x = accum_err_metric[0][0];

h = 0;

for (j = 1; j < last_stop; j++) {

if (accum_err_metric[j][0] < x) {

x = accum_err_metric[j][0];

h = j;

} /* end if */

} /* end ‘j’ for-loop */

#ifdef NORM

/* if the smallest accum. error metric value is > MAXMETRIC, normalize the

accum. errror metrics by subtracting the value of the smallest one from

all of them (making the smallest = 0) and saturate all other metrics

at MAXMETRIC */

if (x > MAXMETRIC) {

for (j = 0; j < number_of_states; j++) {

accum_err_metric[j][0] = accum_err_metric[j][0] — x;

if (accum_err_metric[j][0] > MAXMETRIC) {

accum_err_metric[j][0] = MAXMETRIC;

} /* end if */

} /* end ‘j’ for-loop */

}

#endif

state_sequence[depth_of_trellis] = h;

/* now work backwards from the end of the trellis to the oldest state

in the trellis to determine the optimal path. The purpose of this

is to determine the most likely state sequence at the encoder

based on what channel symbols we received. */

for (j = depth_of_trellis; j > 0; j—) {

sh_col = j + ( sh_ptr — depth_of_trellis );

if (sh_col < 0)

sh_col = sh_col + depth_of_trellis + 1;

state_sequence[j — 1] = state_history[ state_sequence[j] ][sh_col];

} /* end of j for-loop */

/* now figure out what input sequence corresponds to the

optimal path */

*(decoder_output_matrix + t — depth_of_trellis + 1) =

input[ state_sequence[0] ][ state_sequence[1] ];

} /* end of if-statement */

} /* end of ‘t’ for-loop */

for (i = 1; i < depth_of_trellis — m; i++)

*(decoder_output_matrix + channel_length — depth_of_trellis + i) =

input[ state_sequence[i] ] [ state_sequence[i + 1] ];

/* free the dynamically allocated array storage area */

free(channel_output_matrix);

return;

} /* end of function sdvd */

//*******************************************start of function related to sdvd********************************************************************//

/* this initializes a 3-bit soft-decision quantizer optimized for about 4 dB Eb/No.

*/

void init_quantizer(void) {

int i;

for (i = -128; i < -31; i++)

quantizer_table[i + 128] = 7;

for (i = -31; i < -21; i++)

quantizer_table[i + 128] = 6;

for (i = -21; i < -11; i++)

quantizer_table[i + 128] = 5;

for (i = -11; i < 0; i++)

quantizer_table[i + 128] = 4;

for (i = 0; i < 11; i++)

quantizer_table[i + 128] = 3;

for (i = 11; i < 21; i++)

quantizer_table[i + 128] = 2;

for (i = 21; i < 31; i++)

quantizer_table[i + 128] = 1;

for (i = 31; i < 128; i++)

quantizer_table[i + 128] = 0;

}

/* this initializes a quantizer that adapts to Es/No */

void init_adaptive_quant(float es_ovr_n0) {

int i, d;

float es, sn_ratio, sigma;

es = 1;

sn_ratio = (float) pow(10.0, ( es_ovr_n0 / 10.0 ) );

sigma = (float) sqrt( es / ( 2.0 * sn_ratio ) );

d = (int) ( 32 * 0.5 * sigma );

for (i = -128; i < ( -3 * d ); i++)

quantizer_table[i + 128] = 7;

for (i = ( -3 * d ); i < ( -2 * d ); i++)

quantizer_table[i + 128] = 6;

for (i = ( -2 * d ); i < ( -1 * d ); i++)

quantizer_table[i + 128] = 5;

for (i = ( -1 * d ); i < 0; i++)

quantizer_table[i + 128] = 4;

for (i = 0; i < ( 1 * d ); i++)

quantizer_table[i + 128] = 3;

for (i = ( 1 * d ); i < ( 2 * d ); i++)

quantizer_table[i + 128] = 2;

for (i = ( 2 * d ); i < ( 3 * d ); i++)

quantizer_table[i + 128] = 1;

for (i = ( 3 * d ); i < 128; i++)

quantizer_table[i + 128] = 0;

}

/* this quantizer assumes that the mean channel_symbol value is +/- 1,

and translates it to an integer whose mean value is +/- 32 to address

the lookup table «quantizer_table». Overflow protection is included.

*/

int soft_quant(float channel_symbol) {

int x;

x = (int) ( 32.0 * channel_symbol );

if (x < -128) x = -128;

if (x > 127) x = 127;

return(quantizer_table[x + 128]);

}

/* this metric is based on the algorithm given in Michelson and Levesque,

page 323. */

int soft_metric(int data, int guess) {

return(abs(data — (guess * 7)));

}

int nxt_stat(int current_state, int input, int *memory_contents) {

int binary_state[K — 1]; /* binary value of current state */

int next_state_binary[K — 1]; /* binary value of next state */

int next_state; /* decimal value of next state */

int i; /* loop variable */

/* convert the decimal value of the current state number to binary */

deci2bin(current_state, K — 1, binary_state);

/* given the input and current state number, compute the next state number */

next_state_binary[0] = input;

for (i = 1; i < K — 1; i++)

next_state_binary[i] = binary_state[i — 1];

/* convert the binary value of the next state number to decimal */

next_state = bin2deci(next_state_binary, K — 1);

/* memory_contents are the inputs to the modulo-two adders in the encoder */

memory_contents[0] = input;

for (i = 1; i < K; i++)

memory_contents[i] = binary_state[i — 1];

return(next_state);

}

/* this function converts a decimal number to a binary number, stored

as a vector MSB first, having a specified number of bits with leading

zeroes as necessary */

void deci2bin(int d, int size, int *b) {

int i;

for(i = 0; i < size; i++)

b[i] = 0;

b[size — 1] = d & 0x01;

for (i = size — 2; i >= 0; i—) {

d = d >> 1;

b[i] = d & 0x01;

}

}

/* this function converts a binary number having a specified

number of bits to the corresponding decimal number

with improvement contributed by Bryan Ewbank 2001.11.28 */

int bin2deci(int *b, int size) {

int i, d;

d = 0;

for (i = 0; i < size; i++)

d += b[i] << (size — i — 1);

return(d);

}

//*******************************************end of function related to sdvd********************************************************************//

void mexFunction( int nlhs, mxArray *plhs[],

int nrhs, const mxArray *prhs[] )

{

double *channel_output_vector;

int *start_of_pr;

double *snr_pi;

double *channel_length_pi;

size_t bytes_to_copy;

const mwSize dims[]= {1,MSG_LEN};

int Decoder_Output[MSG_LEN ];

//mwSize row = 1;

//mwSize coloumn = 15;

if ( nrhs != 0) {

mexErrMsgIdAndTxt(«MATLAB:sdvd_try_first:rhs»,«This function takes three input arguments.»);

}

if(nlhs>0)

{

mexErrMsgIdAndTxt( «MATLAB:sdvd_try_first:maxlhs»,«Too many output arguments.»);

}

/* Create matrix for the input argument. */

//snr_pi = mxGetPr(prhs[0]);

//channel_output_vector = mxGetPr(prhs[1]);

//channel_output_vector = mxGetPr(prhs[0]);

/* Create matrix for the return argument.(type double) */

sdvd_try_fourth(Decoder_Output);

//plhs[0]= mxCreateNumericArray(2, dims, mxINT32_CLASS, mxREAL); /*this has to be changed according to number bits set by complier to int type */

/*populate the real part of the created array*/

//start_of_pr = (int *)mxGetData(plhs[0]);

//bytes_to_copy = MSG_LEN * mxGetElementSize(plhs[0]);

//memcpy(start_of_pr,Decoder_Output,bytes_to_copy);

return;

}

////*************End of example code *****///////

Do anyone know this window message mean? as blelow:

————————————————————————————————————————-

Windows has triggered a breakpoint in SIS.exe.

This may be due to a corruption of the heap, and indicates a bug in SIS.exe or any of the DLLs it has loaded.

The output window may have more diagnostic information

break Button
Continue Button

————————————————————————————————————————————

This Happen, 

When i click run of the application in VS2005 , at one of the modules where there have Open report, I click open report(Crystal Report) to view.

Then i Close the report, and Then i close the Application.  After than this error window message come out at above.

When i Click break button  , then it say show the assemble code something as below:

———————————————————————————————-

7C90122D  nop              
7C90122E  nop              
7C90122F  nop              
7C901230  int         3    
7C901231  ret              
7C901232  mov         edi,edi 
7C901234  nop              
7C901235  nop              
7C901236  nop  

————————————————————————————————-

  • Moved by

    Tuesday, May 8, 2012 2:56 AM
    (From:Visual Basic Express Edition)

Понравилась статья? Поделить с друзьями:
  • Windows has stopped this device code 43
  • Windows has run out of memory utorrent
  • Windows has recovered from an unexpected shutdown что делать
  • Windows has made corrections to the file system
  • Windows has finished checking the disk please wait