Re: Run-Time Check Failure #2 - Stack around the variable 'foobar' was corrupted.
On Mon, 24 Nov 2008 00:59:24 +0000, "(2b|!2b)==?"
<void-star@ursa-major.com> wrote:
(2b|!2b)==? wrote:
I am receiveing the warning message in the subject of this post,
displayed in a message box when I build and run teh sample code below. I
am using VS2005, and am running on W2k.
I repeat the 'error/warning' message below:
Run-Time Check Failure #2 - Stack around the variable 'foobar' was
corrupted.
I would be grateful if anyone can help point out what I may be doing
wrong, since I have spent the entire evening trying to fgure it out - to
no avail....
Code snippet follows below:
typedef struct
{
double *data;
long size;
long datasize;
long ipos;
} MyArray;
typedef struct
{
MyArray f1, f2, f3, f4, f5, f6, f7;
}MyStruct ;
static long MyAlloc(MyStruct *s1, long size)
{
long i1, i2;
double *data[7];
if (!s1) return -1 ;
for (i1 = 0; i1 < 7; i1++)
{
if ((data[i1] = (double *)calloc(size, sizeof(double))) == NULL)
Your failure to #include stdlib.h causes this statement to invoke
undefined behavior. Putting the cast in was not the correct way to
fix the error.
{
for (i2 = i1 - 1; i2 >= 0; i2--)
free(data[i2]);
memset(s1, 0, sizeof(MyStruct));
Are you absolutely certain that all bits zero is the correct
representation for NULL?
return (-2);
}
}
s1->f2 = s1->f3 = s1->f4 = s1->f5 = s1->f6 = s1->f7 = s1->f1;
s1->f1.data = data[0];
s1->f2.data = data[1];
s1->f3.data = data[2];
s1->f4.data = data[3];
s1->f5.data = data[4];
s1->f6.data = data[5];
s1->f7.data = data[6];
return (0);
}
int main (int argc, char* argv[])
{
Test();
There is no prototype in scope for Test. The compiler will expect it
to return an int which it doesn't.
main is supposed to return an int. The absence of a return statement
caused my test case to return 0x12FEBC. Could this be part of your
problem?
}
void Test()
{
MyStruct foobar = {0};
MyAlloc(&foobar, 100);
You should check the value returned by MyAlloc before attempting to
call MyFree.
MyFree(&foobar);
}
I would really like to understand what is causing this problem ...
The implementation for MyFree is:
void MyFree(MyStruct *s1)
{
if (!s1) return ;
if ( (s1->f1.data) && (s1->f2.data) && (s1->f3.data) &&
(s1->f4.data) && (s1->f5.data) && (s1->f6.data) &&
(s1->f7.data) )
{
free(s1->f1.data);
free(s1->f2.data);
free(s1->f3.data);
free(s1->f4.data);
free(s1->f5.data);
free(s1->f6.data);
free(s1->f7.data);
memset(s1, 0, sizeof(MyStruct));
}
return;
}
--
Remove del for email