Debug error run time check failure 2 stack around the variable

  • Remove From My Forums

 locked

Debugging: Run-Time Check Failure #2 — Stack around the variable ‘LoggerThread’ was corrupted.

  • Question

  • I am getting:

    Run-Time Check Failure #2 — Stack around the variable ‘LoggerThread’ was corrupted.

    I have searched as much as I can for a description of how to diagnose, but I have not found anything. I don’t know how to determine the specific address that is being corrupted. If I knew that, then I could of course set a breakpoint on the condition of that changing.

    I have found many answers about other instances of this error, but nothing that descibes how to diagnose this problem. All other problems were simple enough that the problem could be determined by looking at the code. I have looked at my code extensively and I don’t see a problem. One of the previous answers I have found is Error: Stack corruption around the variable ‘tm’ but the current version of the program uses only default alignment.

    This particular problem is a symptom of a problem that has had various other symptoms, most of which would be more difficult to diagnose. Therefore the problem is probably more subtle than most. I initially encountered the problem in a DLL project, but I wrote a console program to use and test the relevant code. It is the console version that I am debugging.

This problem is caused when you try to write too much data to a particular memory address. Typical causes are writing more to a string buffer than you have room for.

ie

void myfun()

{

    char mybuf[10];



    strcpy(mybuf, "This is definitely more than 10 characters long, it will also cause a Run-Time Check");

}

Another cause of this is when you are using memset/ZeroMemory to initialise a structure or array with the wrong size.

struct MyStruct

{

    int var;

};



void myfun2()

{

    MyStruct ms;



    ZeroMemory(&ms, 20); //since MyStruct is only one variable in the struct this will cause problems

}

A third possible problem is if you are accidentaly moving a pointer.

void myfun3()

{

    int a;

    int*b = &a;



    a++;

    *a = 20;

}

Of course, these problems are not so easy as above to find out, but I hope this will get you on the right track. But this happens and will break at the end of the function that the stack is corrupted in while it is returning. So the best place to look would be in the function that your LoggerThread variable is in.

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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#include <stdio.h>
#include <stdlib.h>
#include <TPerfMeter.h>
#define size 10000
struct tan {
    char ak[14];
    char pl[14];
    int cl;
};
struct elem {
    tan data;
    elem *next;
};
enum bol {NO,YES};
void insert(tan el,elem *ht[],int s);
bol member(tan el,elem *ht[],int s);
void makenull(elem *ht[],int s) {
    int i;
    for (i=0;i<=s;i++)
        ht[i]=NULL;
}
void rebuild(elem *ht[],int s,elem *dht[]) {
    int i;
    elem *curr;
    for (i=0;i<=s;i++) {
        curr=ht[i];
        while (curr!=NULL) {
            insert(curr->data,dht,size*2-1);
            curr=curr->next;
        }
    }
}
int h(tan el,int s) {
    int i;
    int sum1=0,sum2=0;
    for (i=0;i<=14;i++) {
        sum1=sum1+el.ak[i];
        sum2=sum2+el.pl[i];
    }
    return ((sum1*sum2+el.cl)%s);
}
void insert(tan el,elem *ht[],int s) {
    int bucket;//номер сегмента
    elem *oldheader;
    if(!member(el,ht,s)) {
        bucket=h(el,s);
        oldheader=ht[bucket];
        ht[bucket]=new elem();
        ht[bucket]->data=el;
        ht[bucket]->next=oldheader;
    }
}
bol member(tan el,elem *ht[],int s) {
    elem *curr;
    curr=ht[h(el,s)];
    while (curr!=NULL) {
        if (curr->data.ak==el.ak) return (YES);
        else curr=curr->next;
    }
    return (NO);
}
elem *goe(tan el,elem *ht[],int s) {
    elem *curr;
    curr=ht[h(el,s)];
    while (curr!=NULL) {
        if (curr->data.ak==el.ak) return (curr);
        else curr=curr->next;
    }
    return (NULL);
}
void del(tan el,elem *ht[],int s) {
    int bucket=h(el,s);
    elem *curr;
    if (ht[bucket]!=NULL) {
        if (ht[bucket]->data.ak==el.ak)
            ht[bucket]=ht[bucket]->next;
        else {
            curr=ht[bucket];
            while (curr->next!=NULL) {
                if (curr->next->data.ak==el.ak) {
                    curr->next=curr->next->next;
                    return;
                }
                else curr=curr->next;
            }
        }
    }
}
void ini(elem *ht[],elem *dht[],tan *el) {
    makenull(ht,size-1);
    makenull(dht,size*2-1);
    int j;
    for (j=0;j<=14;j++) {
        el->ak[j]=rand()%122;
        el->pl[j]=rand()%122;
    }
    el->cl=rand()%10000;
}
double instime(int elc) {
    elem *ht[size-1];
    elem *dht[size*2-1];
    bol htf=NO,chk=NO;
    int i,n=0;
    tan el;
    TPerfMeter pm;
    double interv=0;
    ini(ht,dht,&el);
    for (i=0;i<=elc-1;i++) {
        if (htf==NO) {
            pm.Start();
            insert(el,ht,size-1);
            interv=interv+pm.Stop();
        }
        else if (chk==NO) {
            rebuild(ht,size-1,dht);
            chk=YES;
            pm.Start();
            insert(el,dht,size*2-1);
            interv=interv+pm.Stop();
        }
        else {
            pm.Start();
            insert(el,dht,size*2-1);
            interv=interv+pm.Stop();
        }
        n++;
        if (n>=2*size-1) htf=YES;
    }
    return (interv);
}
double goet() {
    elem *ht[size-1];
    elem *dht[size*2-1];
    int i;
    tan el;
    TPerfMeter pm;
    double interv=0;
    ini(ht,dht,&el);
    for (i=0;i<=size-1;i++) insert(el,ht,size-1);
    pm.Start();
    goe(el,ht,size-1);
    interv=pm.Stop();
    return interv;
}
double deltime() {
    elem *ht[size-1];
    elem *dht[size*2-1];
    int i;
    tan el;
    TPerfMeter pm;
    double interv=0;
    ini(ht,dht,&el);
    for (i=0;i<=size-1;i++) insert(el,ht,size-1);
    pm.Start();
    del(el,ht,size-1);
    interv=pm.Stop();
    return interv;
}
void tfp() {
    printf("Insert time 10 elements: %fn",instime(10));
    printf("Insert time 100 elements: %fn",instime(100));
    printf("Insert time 1000 elements: %fn",instime(1000));
    printf("Insert time 10000 elements: %fn",instime(10000));
    printf("Insert time 20000 elements(+rebuilding hash table): %fn",instime(20000));
    printf("Delete one element time: %fn",deltime());
    printf("Get one element time: %fn",goet());
    getchar();
    getchar();
}
void main() {
    printf("1. Test for performancen");
    printf("0. Exitn");
    printf("Choose menu point: ");
    switch (getchar()) {
        case '1':tfp();
        case '0':break;
    }
}

Problem

Problem:[

Unable to run a user defined report

Error Message:

Microsoft Visual C++ Debug Library

Debug Error!

Program: C:Program FilesMicrosoft OficeOffice11Excel.exe
Module: C:Program FilesCognosccsControllerXL.xll
File:

Run-Time Check Failure #2 — Stack around the variable ‘sParam’ was corrupted.

Solution:

Solution #1:
The report is corrupted and needs to be recreated. First it will have to be determine if it is the Row or Column definitions that is, in effect, corrupted.

Solution #2:
In some cases it can also help to make a dummy change to the row or column definition, then update and save the report layout.

Steps:]

1. Reports — Create — load the Report — save a copy
2. Substitute the Row Definition, first, save and run the report
3. If the report still errors out,
substitute the Column Definition, save and run the report
4. If the report still errors out, the layout will have to be recreated

Symptom

Microsoft Visual C++ Debug Library

Debug Error!

Program:
C:Program FilesMicrosoft OficeOffice11Excel.exe
Module: C:Program
FilesCognosccsControllerXL.xll
File:

Run-Time Check Failure
#2 — Stack around the variable ‘sParam’ was corrupted.

Resolving The Problem

Solution #1:
The report is corrupted and needs to be recreated. First it will have to be determine if it is the Row or Column definitions that is, in effect, corrupted.

Solution #2:
In some cases it can also help to make a dummy change to the row or column definition, then update and save the report layout.

Steps:1. Reports — Create — load the Report — save a copy
2. Substitute the Row Definition, first, save and run the report
3. If the report still errors out,
substitute the Column Definition, save and run the report
4. If the report still errors out, the layout will have to be recreated

[{«Product»:{«code»:»SS9S6B»,»label»:»IBM Cognos Controller»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Controller»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»Controller (Frango) 8.2″,»Edition»:»»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

Historical Number

1038689

Run-Time Check Failure #2 — Stack around the variable ‘foo’ was corrupted

I’m studying for an exam and this is on my practice test. The question is «Which type of error does the following code fragment cause?»

I was pretty sure there would be no errors, but I also can’t get it to compile in VS13, I get the error:

Run-Time Check Failure #2 — Stack around the variable ‘foo’ was corrupted.

3 Answers 3

Valid indexes for foo are from 0 to MAX-1 inclusive. MAX is past the end of the array.

Your loop runs up to, and including, MAX . This writes beyond the end of the array, corrupting the stack.

Either increase the array size to MAX+1 so that MAX is in range; or change the loop condition to i to stop before reaching MAX .

This problem is caused when you try to write too much data to a particular memory address. Typical causes are writing more to a string buffer than you have room for.

Another cause of this is when you are using memset/ZeroMemory to initialise a structure or array with the wrong size.

A third possible problem is if you are accidentaly moving a pointer.

Of course, these problems are not so easy as above to find out, but I hope this will get you on the right track. But this happens and will break at the end of the function that the stack is corrupted in while it is returning. So the best place to look would be in the function that your LoggerThread variable is in.

Источник

Run-Time Check Failure #2 — Stack around the variable was corrupted

I’ve already saw some questions here at stackoverflow but none of them has solved my problem.

i have that code in C:

When i run the program, i had the error:

Run-Time Check Failure #2 — Stack around the variable ‘str’ was corrupted.

now, i really don’t know what i’m doing wrong there. 🙁

4 Answers 4

The array str can only hold a single char given its initialisation. The call to scanf() will be overwriting the bounds the str causing undefined behaviour, in this case corrupting the stack. You need to decide how large the str array should be and limit the number of characters read to prevent buffer overrun.

To use scanf() you specify the maximum number of characters to read:

You could also use fgets() but would need to remove the new-line character afterwards.

You should not overwrite a constant with user input. Replace char str[] = «» with char * str = malloc( or even learn about safer APIs.

You’re only allocating one byte to store the input. The line

Allocates zero bytes for the string contents and one byte for its null terminator. Instead, do something like

Or whatever the maximum input length will be.

This answer is for everyone that came to C++ from Java/C# or some other modern Object Oriented language.

For me this issue happened for the following reason:

I created my own custom C++ class.

MyClass.h

MyClass.cpp

My intuition was that propA and propB will simply be private properties, invisible from the code outside this class.

The problem turned out to be that I haven’t put propA and propB in MyClass.h . Compiler doesn’t know how much memory it should allocate when MyClass is getting instantiated by callers.

I simply added the properties to the header MyClass.h :

Источник

Debug error run time check failure 2 stack around the variable

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

Run-Time Check Failure #2 — Stack around the variable ‘LoggerThread’ was corrupted.

I have searched as much as I can for a description of how to diagnose, but I have not found anything. I don’t know how to determine the specific address that is being corrupted. If I knew that, then I could of course set a breakpoint on the condition of that changing.

I have found many answers about other instances of this error, but nothing that descibes how to diagnose this problem. All other problems were simple enough that the problem could be determined by looking at the code. I have looked at my code extensively and I don’t see a problem. One of the previous answers I have found is Error: Stack corruption around the variable ‘tm’ but the current version of the program uses only default alignment.

This particular problem is a symptom of a problem that has had various other symptoms, most of which would be more difficult to diagnose. Therefore the problem is probably more subtle than most. I initially encountered the problem in a DLL project, but I wrote a console program to use and test the relevant code. It is the console version that I am debugging.

All replies

This problem is caused when you try to write too much data to a particular memory address. Typical causes are writing more to a string buffer than you have room for.

strcpy(mybuf, «This is definitely more than 10 characters long, it will also cause a Run-Time Check»);

Another cause of this is when you are using memset/ZeroMemory to initialise a structure or array with the wrong size.

ZeroMemory(&ms, 20); //since MyStruct is only one variable in the struct this will cause problems

A third possible problem is if you are accidentaly moving a pointer.

Of course, these problems are not so easy as above to find out, but I hope this will get you on the right track. But this happens and will break at the end of the function that the stack is corrupted in while it is returning. So the best place to look would be in the function that your LoggerThread variable is in.

I have commented out everything in my main function except what is shown in the following, and I still get the same error. The error occurs at the end of the program, after the «return 0; «. In other words, the debugger says that the line that the exception occurs at is the line with the curly braces at the end of main.

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

So you’re saying that the above code produces the error? That is strange, but tells me the problem is inside classLoggerThread.

What I can tell you is that I have experienced this problem several times after switching from VC++ 2003 to VC++ 2005. The cause were some TRACE calls with wrong arguments. The VC++ 2003 debugger didn’t say anything, but in 2005 it raised that error for things like this:

I hope you spot the wrong string format above, or should I say the incorrect number of params for it.

Perhaps it’s something similar for you too.

Marius Bancila wrote:

So you’re saying that the above code produces the error? That is strange, but tells me the problem is inside classLoggerThread.

No, I am saying the opposite. It is crescens2k that said that the problem is in the same function that declares LoggerThread so I posted the code to show that the problem cannot be caused in that function. So I agree with you that it has to be in LoggerThread (classLoggerThread) somewhere.

Marius Bancila wrote:

What I can tell you is that I have experienced this problem several times after switching from VC++ 2003 to VC++ 2005.

This error will never occur using VC 2003 since VC 2003 does not detect the problem. I learned that much by searching for answers.

Marius Bancila wrote:

The cause were some TRACE calls with wrong arguments.

Marius Bancila wrote:

Perhaps it’s something similar for you too.

I have looked for things like that. As I have already said, it is nothing that obvious.

Since you should easily find out which memory address is affected (obviously, it’s either before or after the LoggerThread variable), you could simply set a data breakpoint on it and wait for it to fire.

I tend to calculate the address manually as the debugger’s concept of active scopes isn’t usually very helpful for the cases where you really need a watchpoint. So, just set a breakpoint at your containing the variable. Then get the address of the variable (e.g. Quick Watch «&LoggerThread») and set a data breakpoint on the address causing the problem (again, it will be either before or after the underlying memory of the variable).

Of course, once you leave the function. You should disable or remove the data breakpoint as other code will use the stack for its purposes.

I hope it is that simple. It would be easier if the error message were to say if the problem is before or after.

I think though that it can’t be that simple if the corruption occured after, since that portion of the stack would be constantly changing. Correct? It is not a simple matter of catching modification of the stack at higher addresses than LoggerThread. If the stack is corrupted after, then it seems the corruption occurs so far after (LoggerThread) that the stack memory is not used out there. One thing I am unsure of is the cookies used to detect the corruption. I hope modification of stack memory by the debugger for that purpose does not make things confusing.

If however the stack is corrupted before LoggerThread, then it is strange that there is not a more serious problem, but at least it should be easy to diagnose the problem using breakpoints as you suggest.

I apologize for sounding as if I am criticizing. These questions are among those I was hoping I would get help with. I wiil use breakpoints as you suggest if I don’t figure it out some other way.

I hope it is that simple. It would be easier if the error message were to say if the problem is before or after.

I think though that it can’t be that simple if the corruption occured after, since that portion of the stack would be constantly changing. Correct? It is not a simple matter of catching modification of the stack at higher addresses than LoggerThread. If the stack is corrupted after, then it seems the corruption occurs so far after (LoggerThread) that the stack memory is not used out there. One thing I am unsure of is the cookies used to detect the corruption. I hope modification of stack memory by the debugger for that purpose does not make things confusing.

I haven’t looked at the implementation lately, but I think the mechanism is quite simple actually. The compiler allocates space around variables on the stack and fills it with magic values on function entry. Before leaving the function it generated code checks if the values in the gaps between the real variables is still allocated.

The stack after the function prolog would look something like

saved stack pointers

// either this byte : ((char*)&LoggerThread)-1

// or this byte is overwritten &LoggerThread+1

I’m not sure that what I said was clear. Before and after refer to the location not the time of execution. So after entering the function, just set two data breakpoints. One at ((char*)&LoggerThread)-1 and one at &LoggerThread+1. The stack corruption happens somewhere in the execution of your function (or its callees).

If however the stack is corrupted before LoggerThread, then it is strange that there is not a more serious problem, but at least it should be easy to diagnose the problem using breakpoints as you suggest.

Again before and after where meant to refer to the memory location of the problem. So it’s not really an important distinction. It’s the same type of problem just at slightly different memory locations. So long your problem consistenly repros for the particular function the watchpoints should work just fine — again these shouldn’t be set or at least not active while your function is not executing as the stack space will be allocated for other things. Once execution enters your function the relevant stack space is allocated to that function until it is left.

I apologize for sounding as if I am criticizing. These questions are among those I was hoping I would get help with. I wiil use breakpoints as you suggest if I don’t figure it out some other way.

Hey, these data breakpoints are really not that hard to use 😉

Holger Grund wrote:

Hey, these data breakpoints are really not that hard to use 😉

Actually they are useless for me when I use my own system, which is only 350 MHz. On that system, even very simple programs run noticeably slow and any meaningful debugging is impossible. The problem I am encountering I am developing and debugging using a fast system, so the performance is not likely to be a probem, but that has been a problem for me in the past.

One of us does not understand. First, I must correct what I said before; the stack is used in reverse of what I was thinking. I knew that but I forgot. In other words, for each item local appearing in a function, the addresses decrease. The processor’s stack pointer register is decreased for each item put into it, which makes sense, because then the processor knows there is a problem when the register gets to zero or less.

Yes, I certainly understand that the error message is referring to memory before and after LoggerThread.

There is an important difference between stack memory before a function’s allocations and after.

So for example if we have:

void Level3(int a) <
char Local[4];
std::cout

Note that the addresses decrease. If I create a breakpoint using » *(Local-256)» for 256 elements, then that breakpoint breaks constantly due to normal use of the stack. That makes debugging more difficult; are you aware of that problem?

I have commented out so much code that the problem is not manifesting as the stack corruption problem. There is currently another symptom that I will attempt to diagnose but if I need to, I will recreate this problem to diagnose it.

I managed to cut the code down to a small sample that reproduces the problem, or at least a problem. The symptoms vary, but I think I have been getting clobbered by the same bug, whatever the bug is. See Bizarre bug using std: fstream and TRACEFILE.

Holger Grund wrote:

Hey, these data breakpoints are really not that hard to use 😉

Actually they are useless for me when I use my own system, which is only 350 MHz. On that system, even very simple programs run noticeably slow and any meaningful debugging is impossible. The problem I am encountering I am developing and debugging using a fast system, so the performance is not likely to be a probem, but that has been a problem for me in the past.

You probably haven’t set the breakpoints in the correct way (again you should calculate the address yourself and leave the context empty so that the hardware debug breakpoint registers can be used).

One of us does not understand. First, I must correct what I said before; the stack is used in reverse of what I was thinking. I knew that but I forgot. In other words, for each item local appearing in a function, the addresses decrease. The processor’s stack pointer register is decreased for each item put into it, which makes sense, because then the processor knows there is a problem when the register gets to zero or less.

Yes, I certainly understand that the error message is referring to memory before and after LoggerThread.

There is an important difference between stack memory before a function’s allocations and after.

So for example if we have:

void Level3(int a) <
char Local[4];
std::cout

Note that the addresses decrease. If I create a breakpoint using » *(Local-256)» for 256 elements, then that breakpoint breaks constantly due to normal use of the stack. That makes debugging more difficult; are you aware of that problem?

Unsurprisingly the debugger will watch for modifications of 256 bytes if you tell it to do so. But I don’t see why you would want to do it? It is obvious that this extends into callee stack space. There are only two bytes that you should be interested in: the one before the clobbered local and the one after. Of course, during its lifetime its allocated address will never change. And in debug stack frames its memory location is never shared with any other code. Any modification to it indicates a programming error.

Also, do note that scoped data breakpoints have had some performance problems. Again, if you care about performance calculate the address manually and set a data breakpoint without a C++ scope and make sure you don’t exceed the number of available hardware watchpoint registers (IIRC there are 4 HW breakpoint registers which can watch 1,2 or 4 bytes at a given (aligned?) address). With HW watchpoints you shouldn’t see any performance degradation.

Holger Grund wrote:

You probably haven’t set the breakpoints in the correct way (again you should calculate the address yourself and leave the context empty so that the hardware debug breakpoint registers can be used).

I think I set the breakpoints correctly and the only reason to calculate the addresses myself is if there is an inadequate understanding of how the stack works.

Holger Grund wrote:

There are only two bytes that you should be interested in: the one before the clobbered local and the one after. Of course, during its lifetime its allocated address will never change. And in debug stack frames its memory location is never shared with any other code. Any modification to it indicates a programming error.

If all that is true then it would really help for the documentation to say so. In particular, it would help for the documentation to say that only 1 byte needs to be watched. Also, if debugging was as simple as you say, then it is surprising that the debugger does not show where the problem is. I think the reason the debugger is as vague as it is is not because the VC developers did not bother to provide the information, I think it is because the diagnosis is not as easy as you say. If I am wrong then I apologize for being so difficult.

Holger Grund wrote:

Also, do note that scoped data breakpoints have had some performance problems. Again, if you care about performance calculate the address manually and set a data breakpoint without a C++ scope and make sure you don’t exceed the number of available hardware watchpoint registers (IIRC there are 4 HW breakpoint registers which can watch 1,2 or 4 bytes at a given (aligned?) address). With HW watchpoints you shouldn’t see any performance degradation.

I think you are correct that the hardware breakpoint registers are so much more efficient that it is possible to use data breakpoints even with a slow processor.

I managed to cut the code down to a small sample that reproduces the problem, or at least a problem. The symptoms vary, but I think I have been getting clobbered by the same bug, whatever the bug is. See Bizarre bug using std:fstream and TRACEFILE.

Does the answer in » Bizarre bug using std:: ofstream and TRACEFILE .» help you to solve this question too?

Thanks for your participation

Yes, Rico, that other thread does show and explain the same problem that had the symptoms described in this thread. I currently do not have a version of the program that is getting stack corruption as described here; if I did, I would try some of Holger’s suggestions.

I think however that it is important to make the point that the error is difficult to diagnose. If it is as simple as Holger says, then it would help to have a little something that says something such as what Holger says. I think it is not so simple, so there should be something saying how to diagnose the problem.

One thing that seems easy for the software to do is to be specific about whether the problem is before or after the item in the stack. The diganosis methodology I think varies based on before or after. So to be specific, if it is true that we only need to set a data breakpoint for 1 byte before the item and 1 byte after, then it would help to know that. If however the corruption can occur at a memory location more than 1 byte before (lower in memory) the item, then that makes diagnosis complicated. I think the error message is not clear.

I understand that the error detection is new for VC 2005 and I appreciate the increased security and stability that it supports. I think there is just a little bit more that is needed to make it more useful.

Источник

Adblock
detector

Hello, I’m getting Run-Time Check Failure #2 — Stack around the variable ‘len’ was corrupted. error in /src/diff.h line#152, while debugging the diff_each function.

environment: windows 7 32-bit, libgit2 v0.22.2, visual studio 2013 express

please advise, thanks!

code:

int each_file_cb(const git_diff_delta *delta,float progress,void *payload)
{
    printf("new file:%s n", delta->new_file.path);
    printf("old file:%s n", delta->old_file.path);

    return 0;
}

int each_hunk_cb(
    const git_diff_delta *delta,
    const git_diff_hunk *hunk,
    void *payload)
{

    printf("hunk header:%s n", hunk->header);

    return 0;
}

int each_line_cb(
    const git_diff_delta *delta,
    const git_diff_hunk *hunk,
    const git_diff_line *line,
    void *payload)
{
    printf("line content:%s n", line->content);

    return 0;
}

int git_mysql_tree_diff(git_diff *diff){
    int error;

    error = git_diff_foreach(diff,
        each_file_cb,
        each_hunk_cb,
        each_line_cb,
        NULL);

    return error;
}

Visual Studio Call stack:

>   git2.dll!git_diff_file__resolve_zero_size(git_diff_file * file, git_odb_object * * odb_obj, git_repository * repo) Line 152 C
    git2.dll!diff_file_content_load_blob(git_diff_file_content * fc) Line 235   C
    git2.dll!git_diff_file_content__load(git_diff_file_content * fc) Line 386   C
    git2.dll!diff_patch_load(git_patch * patch, git_diff_output * output) Line 157  C
    git2.dll!diff_patch_generate(git_patch * patch, git_diff_output * output) Line 222  C
    git2.dll!git_diff_foreach(git_diff * diff, int (const git_diff_delta *, float, void *) * file_cb, int (const git_diff_delta *, const git_diff_hunk *, void *) * hunk_cb, int (const git_diff_delta *, const git_diff_hunk *, const git_diff_line *, void *) * data_cb, void * payload) Line 291 C
    git2mysql.dll!git_mysql_tree_diff(git_diff * diff) Line 377 C
    addon.node!GitMysql::Diff(const v8::FunctionCallbackInfo<v8::Value> & args) Line 848    C++
    node.exe!00bc2c55() Unknown
    [Frames below may be incorrect and/or missing, no symbols loaded for node.exe]  
    node.exe!00b8d828() Unknown
    node.exe!00b8b519() Unknown
    node.exe!00b8b4e4() Unknown
    [External Code] 

Run-Time Check Failure #2 — Stack around the variable ‘grade’ was corrupted?

I wrote a program to calculate the average of 10 grades a user inputs. The program works and gives me the average, but at the end when it’s supposed to close I get this error: «Run-Time Check Failure #2 — Stack around the variable ‘grade’ was corrupted.»

I’ve posted the code below. Also, I have to make it calculate median and mode as well. I think I can figure out median, but can anyone help me to get started on mode?

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
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
 {
	//Create an array with 10 elements
	float grade[10];
	int count;
	float tscore = 0;
	//Set precision of Average, will be displayed with a decimal
	double average;
	for (count = 1; count <= 10; count++)
	 {
		cout << "Enter Grade " << count << ": ";
		 {
		cin >> grade[count];
	 }}

	for(count = 1; count <= 10; count++)
		tscore = tscore + grade[count];
	average = tscore/10;
	
	//Assign letter grade corresponding to number grade
	if((average >= 0) && (average < 60))
	{
		cout<<"The average is an F."<<endl;
	}
	else if((average >= 60) && (average < 63))
	{
		cout<<"The average is a D-."<<endl;
	}
	else if((average >= 63) && (average < 67))
	{
		cout<<"The average is a D."<<endl;
	}
	else if((average >= 67) && (average < 70))
	{
		cout<<"The average is a D+."<<endl;
	}
	else if((average >= 70) && (average < 73))
	{
		cout<<"The average is a C-."<<endl;
	}
	else if((average >= 73) && (average < 77))
	{
		cout<<"The average is a C."<<endl;
	}
	else if((average >= 77) && (average < 80))
	{
		cout<<"The average is a C+."<<endl;
	}
	else if((average >= 80) && (average < 83))
	{
		cout<<"The average is a B-."<<endl;
	}
	else if((average >= 83) && (average < 87))
	{
		cout<<"The average is a B."<<endl;
	}
	else if((average >= 87) && (average < 90))
	{
		cout<<"The average is a B+."<<endl;
	}
	else if((average >= 90) && (average < 93))
	{
		cout<<"The average is an A-."<<endl;
	}
	else if((average >= 93) && (average < 97))
	{
		cout<<"The average is an A."<<endl;
	}
	else if((average >= 97) && (average <= 100))
	{
		cout<<"The average is an A+."<<endl;
	}
	else
	{
		cout<<"The average is not between 0 and 100, please reenter the grades with values between 0 and 100."<<endl;
	}

	//Output
	cout << "The average of the ten grades you entered is: " << average << endl;

	system("PAUSE"); 
	return 0;
}

Array indices go from 0 to n-1, not from 1 to n.

Thanks working now. Just one minor problem, it now says Enter Grade 0 for the first grade. Is there any simple way I can change that? If not, it’s fine how it is.

Also, how could I get the mode? Not asking for any code, just point me in the right direction. I know I’m going to have to use count, but not sure how to implement it.

Thanks

Last edited on

You could change it to cout << "Enter Grade " << count+1 << ": ";

As for the mode, there’s an STL algorithm called «count» that will return the amount of times something occurs in a range. Might be worth taking a look at http://www.cplusplus.com/reference/algorithm/count/

Last edited on

Still trying to figure that out, almost have median done though.

I need to move the median = … and the cout below to within the loop, but not sure where. Haven’t gotten a right answer anywhere I put it while testing.

Uses bubble sorting to order and then I take the middle two numbers (since its 10, even) and add them up and divide by 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
	//Calculate Median
	bool done;
	double temp;
	double median;
	while (done == false)
	{
	done = true;  //Done is a boolean value that is set to true by default, if it's left unchanged then we are done
	for (int i = 0; i < 9; i++)
		{
			if (grade[i] > grade[i+1])  //If the next value in the array is smaller than the current value, then we need to swap them.
				{
					temp = grade[i+1];  //Store the second value into a temporary variable first so we don't lose it
					grade[i+1] = grade[i];  //Then set the second value to the current value.
					grade[i] = temp;  //Afterwards place the stored temporary value into the current value
					done = false;   //Since we had to change a value, we are obviously not done, so when the loop completes, it will do another iteration.
	}
	}
	}
	median = (grade[5] + grade[6])/2;
	cout << "The median of the ten grades you entered is: " << median << endl;

Why would you want to move median = and cout into the loop? You only want to calculate it and output it once.

I guess that would be wrong too. Right now I’m getting a Runtime error and it’s outputting a median, but the median is wrong. It’s taking the median of grade[5] and grade[6] without ordering them.

Full code: (Median begins on line 89)

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
// GradeMean.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
 {
	float grade[10]; //Create an array with 10 elements
	int count;
	float tscore = 0;
	double average;
	
	//Input Grades
	for (count = 0; count <= 9; count++)
	 {
		cout << "Enter Grade " << count+1 << ": ";
		 {
		cin >> grade[count];
	 }}

	//Calculate Average
	for(count = 0; count <= 9; count++)
		tscore = tscore + grade[count];
	average = tscore/10;
	
	//Assign letter grade corresponding to number grade
	if((average >= 0) && (average < 60)) 
	{
		cout<<"The average is an F."<<endl;
	}
	else if((average >= 60) && (average < 63))
	{
		cout<<"The average is a D-."<<endl;
	}
	else if((average >= 63) && (average < 67))
	{
		cout<<"The average is a D."<<endl;
	}
	else if((average >= 67) && (average < 70))
	{
		cout<<"The average is a D+."<<endl;
	}
	else if((average >= 70) && (average < 73))
	{
		cout<<"The average is a C-."<<endl;
	}
	else if((average >= 73) && (average < 77))
	{
		cout<<"The average is a C."<<endl;
	}
	else if((average >= 77) && (average < 80))
	{
		cout<<"The average is a C+."<<endl;
	}
	else if((average >= 80) && (average < 83))
	{
		cout<<"The average is a B-."<<endl;
	}
	else if((average >= 83) && (average < 87))
	{
		cout<<"The average is a B."<<endl;
	}
	else if((average >= 87) && (average < 90))
	{
		cout<<"The average is a B+."<<endl;
	}
	else if((average >= 90) && (average < 93))
	{
		cout<<"The average is an A-."<<endl;
	}
	else if((average >= 93) && (average < 97))
	{
		cout<<"The average is an A."<<endl;
	}
	else if((average >= 97) && (average <= 100))
	{
		cout<<"The average is an A+."<<endl;
	}
	else
	{
		cout<<"The average is not between 0 and 100, please reenter the grades with values between 0 and 100."<<endl;
	}

	//Output
	cout << "The average of the ten grades you entered is: " << average << endl;

	//Calculate Median
	bool done;
	double temp;
	double median;
	while (done == false)
	{
	done = true;  //Done is a boolean value that is set to true by default, if it's left unchanged then we are done
	for (int i = 0; i < 9; i++)
		{
			if (grade[i] > grade[i+1])  //If the next value in the array is smaller than the current value, then we need to swap them.
				{
					temp = grade[i+1];  //Store the second value into a temporary variable first so we don't lose it
					grade[i+1] = grade[i];  //Then set the second value to the current value.
					grade[i] = temp;  //Afterwards place the stored temporary value into the current value
					done = false;   //Since we had to change a value, we are obviously not done, so when the loop completes, it will do another iteration.
	}
	}
	}
	median = (grade[5] + grade[6])/2;
	cout << "The median of the ten grades you entered is: " << median << endl;

	//Calculate Mode
	

	system("PAUSE"); 
	return 0;
}

Last edited on

Array indices still go from 0 to n-1. grade[5] and grade[6] are the 6th and 7th elements, respectively.

I know, I changed it to 5 and 6 from 4 and 5. It would be 4 and 5 if I didn’t add 1 to count, so it should be 5 and 6, so I don’t think that’s the problem. Unless I’m missing something, which is definitely possible…

thanks

I don’t see where count comes into play in a expression like grade[5].
In any case, if what you’re trying to say is that the grades don’t get sorted, then that’s because you’re not initializing done, so it could be either true or false initially.

You’re got it backwards, cmorris1441.

In regular numbers:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |

Array indices:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |

Look vertically to see how the numbers correspond, If you want the 4th and 5th elements of the regular numbers, you’ll want to use indices 3 and 4.
so median = (grade[3] + grade[4])/2

Last edited on

You’re right, just changed it and entered 91-100 randomly (once each) and got a median of 94 though…

Also, I’m getting an error:
Run-Time Check Failure #3 — The variable ‘done’ is being used without being initialized.

Program still runs when I click continue.

Last edited on

The variable ‘done’ is being used without being initialized.

Believe it or not, but that’s directly related to the fact that you’re not initializing ‘done’.

It is now, I have 2 programs and was looking at the wrong one. Here’s what I now have, still not getting the median correct.

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
// GradeMean.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
 {
	float grade[10]; //Create an array with 10 elements
	int count;
	float tscore = 0;
	double average;
	
	//Input Grades
	for (count = 0; count <= 9; count++)
	 {
		cout << "Enter Grade " << count+1 << ": ";
		 {
		cin >> grade[count];
	 }}

	//Calculate Mean
	for(count = 0; count <= 9; count++)
		tscore = tscore + grade[count];
	average = tscore/10;
	
	//Assign letter grade corresponding to number grade
	if((average >= 0) && (average < 60)) 
	{
		cout<<"The average is an F."<<endl;
	}
	else if((average >= 60) && (average < 63))
	{
		cout<<"The average is a D-."<<endl;
	}
	else if((average >= 63) && (average < 67))
	{
		cout<<"The average is a D."<<endl;
	}
	else if((average >= 67) && (average < 70))
	{
		cout<<"The average is a D+."<<endl;
	}
	else if((average >= 70) && (average < 73))
	{
		cout<<"The average is a C-."<<endl;
	}
	else if((average >= 73) && (average < 77))
	{
		cout<<"The average is a C."<<endl;
	}
	else if((average >= 77) && (average < 80))
	{
		cout<<"The average is a C+."<<endl;
	}
	else if((average >= 80) && (average < 83))
	{
		cout<<"The average is a B-."<<endl;
	}
	else if((average >= 83) && (average < 87))
	{
		cout<<"The average is a B."<<endl;
	}
	else if((average >= 87) && (average < 90))
	{
		cout<<"The average is a B+."<<endl;
	}
	else if((average >= 90) && (average < 93))
	{
		cout<<"The average is an A-."<<endl;
	}
	else if((average >= 93) && (average < 97))
	{
		cout<<"The average is an A."<<endl;
	}
	else if((average >= 97) && (average <= 100))
	{
		cout<<"The average is an A+."<<endl;
	}
	else
	{
		cout<<"The average is not between 0 and 100, please reenter the grades with values between 0 and 100."<<endl;
	}

	//Output
	cout << "The average of the ten grades you entered is: " << average << endl;

	//Calculate Median
	bool done = false;
	double temp;
	double median;
	while (done == false)
	{
	done = true;  //Done is a boolean value that is set to true by default, if it's left unchanged then we are done
	for (int i = 0; i < 9; i++)
		{
			if (grade[i] > grade[i+1])  //If the next value in the array is smaller than the current value, then we need to swap them.
				{
					temp = grade[i+1];  //Store the second value into a temporary variable first so we don't lose it
					grade[i+1] = grade[i];  //Then set the second value to the current value.
					grade[i] = temp;  //Afterwards place the stored temporary value into the current value
					done = false;   //Since we had to change a value, we are obviously not done, so when the loop completes, it will do another iteration.
	}
	}
	}
	median = (grade[3] + grade[4])/2;
	cout << "The median of the ten grades you entered is: " << median << endl;

	//Calculate Mode
	

	system("PAUSE"); 
	return 0;
}

Last edited on

The two middle elements are the ones with indices 4 and 5.

Okay, the confusion ends here. I didn’t count to the middle of the array properly.
median = (grade[4] + grade[5])/2
Reference my little diagram above. Numbers correspond vertically. We both should have seen that. Lol.

Wasn’t thinking when I corrected it earlier. Thanks. Median and Mean both work now.

Thanks Athar and Thumper for all the help.

Oops, disregard. :)

Last edited on

Topic archived. No new replies allowed.

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

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

  • 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 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии