Like Tree6Likes

Debugging help :(

This is a discussion on Debugging help :( within the C Programming forums, part of the General Programming Boards category; I don't know why Matticus got a segmentation fault, perhaps he made an error. Yeah, I'm a bit rusty with ...

  1. #31
    Registered User
    Join Date
    Jun 2011
    Posts
    2,706
    I don't know why Matticus got a segmentation fault, perhaps he made an error.
    Yeah, I'm a bit rusty with copy/paste. Sometimes, code gets mysteriously changed in the process.

    Okay, I'm done feeding the troll. This one won't listen to reason or constructive advice anyway.

  2. #32
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by Matticus View Post
    Yeah, I'm a bit rusty with copy/paste. Sometimes, code gets mysteriously changed in the process.

    Okay, I'm done feeding the troll. This one won't listen to reason or constructive advice anyway.
    OK I said perhaps, all I am saying it it ran on my machine which it did and still does.
    I don't know why it had a fault on your machine, here are numerous reason why that could be, one is an error on your fault
    but there may be more likely reasons.

    Why are people having a go at me for trying to help?

    If you don't like my posts then nobody is forcing your to read them.

  3. #33
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Code:
    #include <stdio.h>
    #include <math.h>
    #include <conio.h>
      
      
    typedef double real;
      
      
    typedef struct
    {
        real xpos;
        real ypos;
        real zpos;
          
        real uvel;
        real vvel;
        real wvel;
          
        real omegax;
        real omegay;
        real omegaz;
          
        real radius;
        real mass;
          
    } sphere;
      
      
    void update_position(sphere *ball, real dt)
    {
       //(*ball).xpos
       ball->xpos=ball->xpos + dt*ball->vvel;
       //ypos,zpos 
    }
      
      
    void detect_ball(sphere *ball1, sphere *ball2, real *pdist)
    {
          
        *pdist=sqrt((ball2->xpos-ball1->xpos)*(ball2->xpos-ball1->xpos)+
                   (ball2->ypos-ball1->ypos)*(ball2->ypos-ball1->ypos));
                     
    //        if ( dist<= (ball1->radius + ball2->radius) +0.0075 )
    //        {
    //            if ( dist>= ball1->radius + ball2->radius -0.0075   )
    //            { 
    //            *ptime=0;
    //            }
    //        }
      
      
    }
      
      
    int main(int argc, char *argv)
    {
        real dt=0.01;
        real t, dist1, tmax=1, mlimit, firstvvel, gap=1.5,  dist[2], ballmatxpos[101][2];
        int nballs=1 ;
        int i,j,m,k;
        sphere *ball;
           
       
        mlimit=tmax/dt;
        //initialise positions
        for(i=0;i<=nballs;i++)
        {
      
    ball=(sphere *)malloc(nballs*sizeof(sphere));
           ball[i].radius=0.5;
    //         ball[i].ypos=0.0; 
           ball[i].xpos=(real) i * ((real)2.0*(ball[i].radius + gap));
    
    
     ball[i].xpos=0.0;
           ball[i].ypos=0.0;
             
    //	ball[i].xpos=(real)( (real)i * (real)(2.0*ball[i].radius + gap));
    
    
           ball[i].uvel=1.0;
           ball[0].vvel=1.0;
           ball[1].vvel=0.0;
        }
          
        //pendulum to be released
       // ball[0].xpos=0;
        //ball[0].ypos=0;
      //  firstvvel=0;
          
        //timestep loop
        t=0.0;
        dist1=0.0;
        while(t<tmax)
        {
            for(m=0;m<=mlimit;m++)
           {
           //update position
            for(i=0;i<=nballs;i++)
            {
                  update_position(&(ball[i]), dt);
            }
           //collision detection
            for(i=0;i<=nballs;i++)
            {
                for(j=0;j<=nballs;j++)
                {
                    detect_ball(&(ball[i]),&(ball[j]), &dist1);    
                                   
                  if ( dist1 <= (ball[i].radius + ball[j].radius) +0.075 )
                    {
                       if ( dist1 >= (ball[i].radius + ball[j].radius) -0.075   )
                        {
                 //  ball2->uvel=ball1->vvel;
                    //yes collision, modify velocities and rotation rates 
                        t=0;
                         }
                    }
                }
            }
              
            ballmatxpos[m][0]=t;
            ballmatxpos[m][1]=ball[0].xpos;
      
      
       printf("In this case, initial velocity= %3.4lf with t=%3.4lf \n", ballmatxpos[m][0], t ); 
                                     
            t+=dt;  
            }
        }
          
      
      
    //    ---------------//-------------------------
          FILE *pFile1;
             FILE *pFile2;
             pFile1 = fopen("graphing3.txt", "w");
             pFile2 = fopen("graphing4.txt", "w");
             if (pFile1 != NULL)
            {
                 for(m=0;m<=mlimit;m++)
                 {
             fprintf( pFile1, " %3.4lf \n ", ballmatxpos[m][0]);
                  }
          fprintf( pFile1,"\n");
          fclose(pFile1);
            }
          if (pFile2 != NULL)
            {
                 for(m=0;m<=mlimit;m++)
                 {
             fprintf( pFile2, " %3.4lf  \n", ballmatxpos[m][1]);
             }
           fprintf( pFile2,"\n");
          fclose(pFile2);    
           }
                     else
            {
                printf("inda dapat print bro");
           }
      
      
      
      
      
      
    //  -----------------------------------------------------
      
      
      
      
          
        getch();
        return 0;
    }
    The above also runs but not it you comment out the
    ball[i].xpos=0.0;
    Maybe that's a clue I don't know.

  4. #34
    Registered User
    Join Date
    Dec 2012
    Posts
    17
    Your comments and help is exponentially building my skills up, Thanks!
    Last edited by Zul56; 01-11-2013 at 05:14 PM.

  5. #35
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Code:
    #include <stdio.h>
    #include <math.h>
    #include <conio.h>
      
      
    typedef double real;
      
      
    typedef struct
    {
        real xpos;
        real ypos;
        real zpos;
          
        real uvel;
        real vvel;
        real wvel;
          
        real omegax;
        real omegay;
        real omegaz;
          
        real radius;
        real mass;
          
    } sphere;
      
      
    void update_position(sphere *ball, real dt)
    {
       //(*ball).xpos
       ball->xpos=ball->xpos + dt*ball->vvel;
       //ypos,zpos 
    }
      
      
    void detect_ball(sphere *ball1, sphere *ball2, real *pdist)
    {
          
        *pdist=sqrt((ball2->xpos-ball1->xpos)*(ball2->xpos-ball1->xpos)+
                   (ball2->ypos-ball1->ypos)*(ball2->ypos-ball1->ypos));
                     
    //        if ( dist<= (ball1->radius + ball2->radius) +0.0075 )
    //        {
    //            if ( dist>= ball1->radius + ball2->radius -0.0075   )
    //            { 
    //            *ptime=0;
    //            }
    //        }
      
      
    }
      
      
    int main(int argc, char *argv)
    {
        real dt=0.01;
        real t, dist1, tmax=1, mlimit, firstvvel, gap=1.5,  dist[2], ballmatxpos[101][2];
        int nballs=1 ;
        int i,j,m,k;
        sphere *ball;
           
       ball=(sphere *)malloc(nballs*sizeof(sphere));
        mlimit=tmax/dt;
        //initialise positions
        for(i=0;i<=nballs;i++)
        {
      
    
           ball[i].radius=0.5;
    //         ball[i].ypos=0.0; 
           ball[i].xpos=(real) i * ((real)2.0*(ball[i].radius + gap));
    
    
    ball[i].xpos=0.0;
           ball[i].ypos=0.0;
             
    //	ball[i].xpos=(real)( (real)i * (real)(2.0*ball[i].radius + gap));
    
    
           ball[i].uvel=1.0;
           ball[i].vvel=1.0;
           ball[1].vvel=0.0;
        }
          
        //pendulum to be released
       // ball[0].xpos=0;
        //ball[0].ypos=0;
      //  firstvvel=0;
          
        //timestep loop
        t=0.0;
        dist1=0.0;
        while(t<tmax)
        {
            for(m=0;m<=mlimit;m++)
           {
           //update position
            for(i=0;i<=nballs;i++)
            {
                  update_position(&(ball[i]), dt);
            }
           //collision detection
            for(i=0;i<=nballs;i++)
            {
                for(j=0;j<=nballs;j++)
                {
                    detect_ball(&(ball[i]),&(ball[j]), &dist1);    
                                   
                  if ( dist1 <= (ball[i].radius + ball[j].radius) +0.075 )
                    {
                       if ( dist1 >= (ball[i].radius + ball[j].radius) -0.075   )
                        {
                 //  ball2->uvel=ball1->vvel;
                    //yes collision, modify velocities and rotation rates 
                        t=0;
                         }
                    }
                }
            }
              
            ballmatxpos[m][0]=t;
            ballmatxpos[m][1]=ball[0].xpos;
      
      
       printf("In this case, initial velocity= %3.4lf with t=%3.4lf \n", ballmatxpos[m][0], t ); 
                                     
            t+=dt;  
            }
        }
          
      
      
    //    ---------------//-------------------------
          FILE *pFile1;
             FILE *pFile2;
             pFile1 = fopen("graphing3.txt", "w");
             pFile2 = fopen("graphing4.txt", "w");
             if (pFile1 != NULL)
            {
                 for(m=0;m<=mlimit;m++)
                 {
             fprintf( pFile1, " %3.4lf \n ", ballmatxpos[m][0]);
                  }
          fprintf( pFile1,"\n");
          fclose(pFile1);
            }
          if (pFile2 != NULL)
            {
                 for(m=0;m<=mlimit;m++)
                 {
             fprintf( pFile2, " %3.4lf  \n", ballmatxpos[m][1]);
             }
           fprintf( pFile2,"\n");
          fclose(pFile2);    
           }
                     else
            {
                printf("inda dapat print bro");
           }
      
      
      
      
      
      
    //  -----------------------------------------------------
      
      
      
      
          
        getch();
        return 0;
    }

    graphing3.txt
    Code:
     0.9600 
      0.9700 
      0.9800 
      0.9900 
      1.0000 
      1.0100 
      1.0200 
      1.0300 
      1.0400 
      1.0500 
      1.0600 
      1.0700 
      1.0800 
      1.0900 
      1.1000 
      1.1100 
      1.1200 
      1.1300 
      1.1400 
      1.1500 
      1.1600 
      1.1700 
      1.1800 
      1.1900 
      1.2000 
      1.2100 
      1.2200 
      1.2300 
      1.2400 
      1.2500 
      1.2600 
      1.2700
    graphing4.txt
    Code:
     2.0300  
     2.0400  
     2.0500  
     2.0600  
     2.0700  
     2.0800  
     2.0900  
     2.1000  
     2.1100  
     2.1200  
     2.1300  
     2.1400  
     2.1500  
     2.1600  
     2.1700  
     2.1800  
     2.1900  
     2.2000  
     2.2100  
     2.2200  
     2.2300  
     2.2400  
     2.2500  
     2.2600  
     2.2700  
     2.2800  
     2.2900  
     2.3000  
     2.3100  
     2.3200
    I wish to apologise for this spam
    Unfortunately it requires
    ball[i].xpos=0.0;
    to be after
    ball[i].xpos=(real) i * ((real)2.0*(ball[i].radius + gap));

    Which overwrite what the OP intended somewhat but if that line was sort it might be OK.
    Last edited by esbo; 01-11-2013 at 05:30 PM.
    Zul56 likes this.

  6. #36
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Code:
    ball[i].uvel=1.0;
    ball[0].vvel=1.0;<----------- obviously the [0] should be [i]
    ball[1].vvel=0.0;

  7. #37
    Registered User
    Join Date
    Dec 2012
    Posts
    17
    Yes. The main solution to make it work is to put the malloc line in the "i" loop. (Why?). And, I also need to improve my code as advised. Thank you, God bless everyone!; Roger and out!

  8. #38
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by Zul56 View Post
    Yes. The main solution to make it work is to put the malloc line in the "i" loop. (Why?). And, I also need to improve my code as advised. Thank you, God bless everyone!; Roger and out!
    It has to be in the loop because you malloc only makes space for one sphere.
    If you want more spheres you have to malloc a new sphere data space (memory) every time.
    If you do not, you have not created and free space to write to and it will over write whatever it finds ultimately causing a crash.
    I would add it should not work it makes no sense to me as it is.
    It is just lucky it works it needs a proper solution IMO.
    Last edited by esbo; 01-11-2013 at 05:49 PM.

  9. #39
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Just seen some other stuff in the program which explains a lot.
    So some of the stuff I said may not be correct as I made some assumptions about what the OP was doing.
    Basically it would not have been how I would have done it to recall doing it in the past.
    Malloc is being used in the wrong way. Or at least not as I would have done it but many ways to crack an egg.
    Last edited by esbo; 01-11-2013 at 07:06 PM.

  10. #40
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,676
    EDIT: esbo, I missed your most recent post (#39) because I was writing this at the time and got held up at work (for almost an hour!). So I didn't consider what that post says in this reply, so please read it as such.

    @esbo:
    I'm not "having a go" at you, merely trying to make sure Zul56 gets the best, correct advice. Matticus did not do anything wrong. Your code has a bug. Actually, it's the same bug as the OP had, that I pointed out earlier. We like that people want to help. I am not trying to be rude or mean here, but I think you are a little out of your depth, and you're giving bad/incorrect advice. It might be better to give no advice than bad advice.

    @everybody:
    The first bug is the array out of bounds problem, that first for loop in main needs to be a < not a <=. The reason Matticus and I have a seg fault and you guys don't is a matter of chance. That array out of bounds corrupts some memory, and memory corruption results in undefined behavior. By it's very nature, undefined behavior may be anything or nothing. It may be a crash, incorrect output, or may appear normal. It might not even present itself the same way every time on the same machine. It's like a bomb, just waiting to go off. No matter whether it appears to work, that code is buggy and needs to be fixed.

    esbo's code may output the files, as the OP wanted, however it retains the out of bounds bug, introduces a memory leak, and another bug.

    Technically the OP had a memory leak to begin with (since he never called free(ball) at the end of the program), but moving the malloc inside the loop makes it worse, and calling free(ball) at the end wont fix it. If nballs is anything other than 1, every time through that loop, your code would allocate more memory, and assign the value to ball. So if nballs was 2, you malloc twice, storing both results in ball. The second time through the loop, you overwrite the pointer returned by the first call to malloc, and lose it forever. There is no way to get it back and free it. That is a memory leak.

    Even if you fix the first bug, as I suggested, there would still be a problem if nballs was anything other than 1. Let's use 3 for this example. The first time through the loop, i is 0, you allocate an array of 3 balls (ball[0], ball[1] and ball[2]). You initialize ball[i], which is ball[0]. Then i is incremented and becomes 1. You then allocate a new array of 3 balls, losing the old one. i is 1, so when you initialize ball[i], you initialize ball[1], but not ball[0] or ball[2]. Remember, it's a new array (you called malloc again), and this array has a ball[0] that is uninitialized. i is incremented again, and is 2. Similarly, you allocate a new array, now you've lost the first two. You initialize ball[i], which is ball[2]. ball[0] and ball[1] in the new array are uninitialized. Any time you use ball[0], you're using random garbage values, because it's not initialized. Now, we jump down to this line:
    Code:
     ballmatxpos[m][1]=ball[0].xpos;
    Now you've assigned bad values to ballmatxpos[m][1], and on this line:
    Code:
    fprintf( pFile2, " %3.4lf  \n", ballmatxpos[m][1]);
    You will be printing those incorrect values to your file.

    The original malloc call, outside the loop is fine. If nballs is more than 1, it will allocate space for more than 1 sphere. That is the point of the nballs * part of the malloc call. This always allocates one sphere object:
    Code:
    ball = malloc(sizeof(sphere));
    This always allocates nballs number of sphere objects:
    Code:
    ball = malloc(nballs * sizeof(sphere));
    Use the second one, it will always be correct. Then, make sure all your loops that access that array, start with i = 0; and use i < nballs; as a stopping condition (again, note just a plain "less than", not "less than or equal to").

  11. #41
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by anduril462 View Post
    EDIT: esbo, I missed your most recent post (#39) because I was writing this at the time and got held up at work (for almost an hour!). So I didn't consider what that post says in this reply, so please read it as such.

    Not too sure what I said in post 39 so bear in mind I may not remember what I said.


    Quote Originally Posted by anduril462 View Post
    @esbo:
    I'm not "having a go" at you, merely trying to make sure Zul56 gets the best, correct advice. Matticus did not do anything wrong. Your code has a bug. Actually, it's the same bug as the OP had, that I pointed out earlier. We like that people want to help. I am not trying to be rude or mean here, but I think you are a little out of your depth, and you're giving bad/incorrect advice. It might be better to give no advice than bad advice.

    My code produced the files which the the OP wanted produced.
    If you consider his code doing what he wanted it to do a 'bug' fair enough that is not my definition, my definition is when the code does not do do what you want it to do so we will have to differ on that.
    My code thus did not have a bug as such although there may well be bugs in the OP code, I concede that.


    Quote Originally Posted by anduril462 View Post
    @everybody:
    The first bug is the array out of bounds problem, that first for loop in main needs to be a < not a <=. The reason Matticus and I have a seg fault and you guys don't is a matter of chance. That array out of bounds corrupts some memory, and memory corruption results in undefined behavior. By it's very nature, undefined behavior may be anything or nothing. It may be a crash, incorrect output, or may appear normal. It might not even present itself the same way every time on the same machine. It's like a bomb, just waiting to go off. No matter whether it appears to work, that code is buggy and needs to be fixed.
    I was not particular concerned with that part of the code rather just in getting the files the OP wanted, that is what he requested, that is what he got. He didn't request help sorting out other bugs in the code.


    Quote Originally Posted by anduril462 View Post
    esbo's code may output the files, as the OP wanted, however it retains the out of bounds bug, introduces a memory leak, and another bug.
    Not my code though is it? I don't write it, it's the OP's code.
    It's a bit underhand to imply they are my bugs when I didn't write the code. I have no problem owning up to bugs in my code however rare they may be but I won't have other people bugs attributed to me thank you very much!!!!

    Quote Originally Posted by anduril462 View Post
    Technically the OP had a memory leak to begin with (since he never called free(ball) at the end of the program), but moving the malloc inside the loop makes it worse,
    Well basically I would not have done the program as he had done in the first place so I don't think you can say it made it worse, especially when it made the program work.
    Granted I would have made further changes if required by the OP but I just wanted to get the files he requested.
    I would have made further improvements to that and indeed have although not posted them yet.


    Quote Originally Posted by anduril462 View Post
    and calling free(ball) at the end wont fix it. If nballs is anything other than 1, every time through that loop, your code would allocate more memory, and assign the value to ball. So if nballs was 2, you malloc twice, storing both results in ball. The second time through the loop, you overwrite the pointer returned by the first call to malloc, and lose it forever. There is no way to get it back and free it. That is a memory leak.
    It was only my intention to get the files the OP requested, he never mentioned a memory leak being a problem.



    Quote Originally Posted by anduril462 View Post
    Even if you fix the first bug, as I suggested, there would still be a problem if nballs was anything other than 1. Let's use 3 for this example. The first time through the loop, i is 0, you allocate an array of 3 balls (ball[0], ball[1] and ball[2]). You initialize ball[i], which is ball[0]. Then i is incremented and becomes 1. You then allocate a new array of 3 balls, losing the old one. i is 1, so when you initialize ball[i], you initialize ball[1], but not ball[0] or ball[2]. Remember, it's a new array (you called malloc again), and this array has a ball[0] that is uninitialized. i is incremented again, and is 2. Similarly, you allocate a new array, now you've lost the first two. You initialize ball[i], which is ball[2]. ball[0] and ball[1] in the new array are uninitialized. Any time you use ball[0], you're using random garbage values, because it's not initialized. Now, we jump down to this line:
    Code:
     ballmatxpos[m][1]=ball[0].xpos;
    Now you've assigned bad values to ballmatxpos[m][1], and on this line:
    Code:
    fprintf( pFile2, " %3.4lf  \n", ballmatxpos[m][1]);
    You will be printing those incorrect values to your file.

    The original malloc call, outside the loop is fine. If nballs is more than 1, it will allocate space for more than 1 sphere. That is the point of the nballs * part of the malloc call. This always allocates one sphere object:
    Code:
    ball = malloc(sizeof(sphere));
    This always allocates nballs number of sphere objects:
    Code:
    ball = malloc(nballs * sizeof(sphere));
    Use the second one, it will always be correct. Then, make sure all your loops that access that array, start with i = 0; and use i < nballs; as a stopping condition (again, note just a plain "less than", not "less than or equal to").
    In reality there is little point in the OP using malloc at all as he knows exactly how much memory the program before the program runs.
    So he may as well have just defined a structure of sphere of size nballs and forgot all about malloc at all.


    This explains why I moved the malloc inside the loop, I thought there must be an undefined number of balls and that the balls would be defined dynamically at run time, which is pretty much what malloc is for. That is why I moved it into the loop because to malloc just one occurrence of an object is rather pointless.
    I mean in that situation the memory should really be allocated at compile time not run time.

    I just basically addressed the specific problem the OP mentioned.
    He didn't ask for help with any other bugs so I did not see any point in taking him somewhere he didn't want to go. It's like helping an old lady across the road and then finding out she didn't want to go there in the first place. Unnecessary. I just assumed the OP felt capable of sorting other the other problems once they got the output form the files.


    Anyhow as I said I would not have done it that way in the first place, I might have gone on to demonstrate how malloc is intended to be used. Some of the point you mention are minor programming details, the bigger issue to me is that malloc is being used rather inappropriately in the first place. It is intended for dynamic memory allocation and the program as it stands has no requirement to do that.
    it's a bit like using a screw driver to hammer in a nail, that's not what it's for really.

  12. #42
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by Zul56 View Post
    Yes. The main solution to make it work is to put the malloc line in the "i" loop. (Why?). And, I also need to improve my code as advised. Thank you, God bless everyone!; Roger and out!
    The original code only allocated memory for one ball.
    However you wrote the data for two balls to memory with out reserving memory for them!!
    Thus you overwrote some data in advertantly.
    As it happens the data after you original and only malloc looks to have been the file pointers!!
    That is why you had no files!!!

    However when I put the malloc inside the loop I created space for two balls and as it happens the data was written into that space and nothing unintended was overwritten. Indeed each time it looped a new area of memory would have been created.
    Actually it may just have been luck that it worked, I am confusing myself now!!!

    Or oh well no, by putting it inside the loop the memory was allocated at run time. I need a diagram really


    The way you did it you had.

    [memory space for one ball M1 ][file pointer1][file pointer2]


    However the way I did it you had
    [file pointer1][file pointer2][memory space for one ball M1 ][memory space for one ball M2]

    Now when you ran you code it wrote the first ball in memory space and the next ball immediately after it

    [memory space for one ball M1 ][file pointer1 ][file pointer2 ]
    [you wrote ball one above ][ you wrote ball two here above (oh dear!! ]

    Thus the second ball over wrote the file pointers!!

    However when I did it.

    [file pointer1][file pointer2][memory space for one ball M1 ][memory space for one ball M2]
    [ you write no balls here ][ you wrote ball one here ][ and ball 2 here - so no problem]

    So doing as I did you never over wrote the file pointers. That is why it worked.

    But you were lucky, had you done any other memory allocation operations between writing the ball you might have over written stuff you didn't want to. However as you didn't it all worked well.

    It could be described as "a bug waiting to happen".

    It is however quite an interesting point.

    Actually had you merely declared your File pointer as global my betting is your code would have worked!!

    Some people here condemn the use of global variable for reasons they cannot justify fully, they say it is bad practise
    because someone told them it was. It isn't in my opinion, it depends.

    In a way it worked but for somewhat all the wrong reasons.

    Actually I tried moving the FILE declaration and it made not difference so you can ignore the above lol - what a waste of time!!

    It seems the main thing which causes a problem is this line.

    ball[i].xpos=(real) i * (2*ball[i].radius + gap);

    For some reason.


    Actually what I wrote above is half right if you ignore the bit about the file pointed bit.
    Basically inside the loop you do two mallocs making enough space for the two balls you write, so it writes to valid space.
    If you leave it outside the loop you only make space for one ball so there is nowhere valid to write the second hence the error.

    I think actually malloc uses a different memory space, the heap as opposed to the stack where other variables are created.

    Anyhow, I think i better wind up!!!!!!!
    Last edited by esbo; 01-11-2013 at 09:39 PM.

  13. #43
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Just one more thing, commenting out or simplifying the follow code seem to make my moving the malloc inside the loop work.


    Code:
    ball[i].xpos=(real) i * (2*ball[i].radius + gap);

    This may be because doing the calculation shifts memory around a bit.
    Without it all the data required may be in registers meaning no memory shift, thus the memory is allocated in the right place.

    So you don't want to do it as I suggested , at least not without making further modifications, so I would revert back to the original format outside the loop. I had made some assumptions about the program which were wrong.

  14. #44
    Registered User
    Join Date
    Dec 2012
    Posts
    17
    Quote Originally Posted by esbo View Post
    The way you did it you had.

    [memory space for one ball M1 ][file pointer1][file pointer2]


    However the way I did it you had
    [file pointer1][file pointer2][memory space for one ball M1 ][memory space for one ball M2]

    Now when you ran you code it wrote the first ball in memory space and the next ball immediately after it

    [memory space for one ball M1 ][file pointer1 ][file pointer2 ]
    [you wrote ball one above ][ you wrote ball two here above (oh dear!! ]

    Thus the second ball over wrote the file pointers!!

    However when I did it.

    [file pointer1][file pointer2][memory space for one ball M1 ][memory space for one ball M2]
    [ you write no balls here ][ you wrote ball one here ][ and ball 2 here - so no problem]

    So doing as I did you never over wrote the file pointers. That is why it worked.
    I don't really get this. Can you illustrate this in terms of the code? And lets say for 10balls?

  15. #45
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by Zul56 View Post
    I don't really get this. Can you illustrate this in terms of the code? And lets say for 10balls?
    I would not worry to much if you don't get it, it's not actually correct anyway, although it could have been.

    What I will try and do is break it down into a few points. It might help me understand what I am talking about.

    1 Firstly it is wrong, I thought you were overwriting your file pointers, but I don't think that's the case anymore. computer uses to separate areas of memory, the heap and the stack. Most variables are stored on the stack, apart from memory allocated by malloc, which are stored on the heap. I forgot mallocs uses the heap, so as they used the heap there is no way they could over write your file pointers which are stored on the heap.

    2. Secondly I am not sure sure moving the malloc inside the loop did work because that is not the only thing I did. Fortunately I actually posted the code here and the results so there can be no doubt about it.

    My code, note I lost a line I lost this line
    Code:
     ball[i].xpos=(real) i * (2*ball[i].radius + gap);
    as well as moving the malloc inside.


    Code:
        mlimit=tmax/dt;
        //initialise positions
        for(i=0;i<=nballs;i++)
        {
      
    ball=(sphere *)malloc(nballs*sizeof(sphere));
           ball[i].radius=0.5;
             ball[i].ypos=0.0; 
           ball[i].ypos=0.0;
             
           ball[i].uvel=1.0;
           ball[0].vvel=1.0;
           ball[1].vvel=0.0;
        }
    Your original code.

    Code:
        ball=(sphere *)malloc(nballs*sizeof(sphere));
        mlimit=tmax/dt;
        //initialise positions
        for(i=0;i<=nballs;i++)
        {
           ball[i].radius=0.5;
           ball[i].xpos=(real) i * (2*ball[i].radius + gap); <-------I lost this line too
           ball[i].ypos=0.0; 
            
           ball[i].uvel=1.0;
           ball[0].vvel=1.0;
           ball[1].vvel=0.0;
        }
    It is losing that line which was key to making the code work not the malloc (I think!!)

    In fact I moved the malloc back outside the loop and it still works here is the bit of code which also worked.

    Code:
        ball=(sphere *)malloc(nballs*sizeof(sphere));
        
        mlimit=tmax/dt;
        //initialise positions
        for(i=0;i<=nballs;i++)
        {
     
           ball[i].radius=0.5;
     //    ball[i].xpos=(real) i * (2*ball[i].radius + gap);
           ball[i].ypos=0.0; 
            
           ball[i].uvel=1.0;
           ball[i].vvel=1.0;
           ball[i].vvel=0.0;
        }
    So you were right not to understand it because that was was not a correct explanation.

    What perhaps is more interesting is why commenting out that line works.
    It may be due to a similar reason as I tried to explain (and you could not understand but it required further investigation as to why that made the program work (although it will be producing the wrong result as the line is commented out, but at least the file are produced).

    I have two theories as to why commenting out that line made the porgram worked.

    1.) There is something fundamentally wrong with that line.

    2.) There is nothing wrong with that line, but having it in the code causes a shift in the alignment of the memory which exposes and otherwise hidden fault.

    It requires further investigation to find out which of the two is the case. I will investigate further and post the results if I find out why.
    I find how the memory is aligned an interesting subject, it can help understand some bugs. I remember working on one program which worked on a lot of different machine apart from one and it was puzzling as to why it did not work on that machine.
    It turned out the machine aligned the memory differently I think the stack worked in the opposite direction whcih cause the return address from a function call to be over written (at least I think that was the problem!!).

    I actually put in a test line outside the loop, slight lodified using 0 instead of i
    to make that line compute and it seems to work fine so the line in itself does not seem to be a problem.

    What I think is the problem is that........well I am not sure now because there is no malloc inside the loop so I can't think of anything at the moment!!!


    Code:
        ball=(sphere *)malloc(nballs*sizeof(sphere));
        
        mlimit=tmax/dt;
        //initialise positions
        for(i=0;i<=nballs;i++)
        {
     
           ball[i].radius=0.5;
     //    ball[i].xpos=(real) i * (2*ball[i].radius + gap);
           ball[i].ypos=0.0; 
            
           ball[i].uvel=1.0;
           ball[i].vvel=1.0;
           ball[i].vvel=0.0;
        }
    
    
    ball[0].xpos=(real) 0 * (2*ball[0].radius + gap); <<------test line added
    Last edited by esbo; 01-12-2013 at 01:04 PM.

Page 3 of 4 FirstFirst 1234 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help Debugging (ADT)
    By minidragon in forum C Programming
    Replies: 16
    Last Post: 08-08-2011, 07:39 PM
  2. Debugging Dev C++
    By tuurb046 in forum Tech Board
    Replies: 10
    Last Post: 08-16-2007, 01:51 PM
  3. debugging
    By St0rM-MaN in forum Tech Board
    Replies: 13
    Last Post: 07-06-2007, 03:03 PM
  4. help debugging
    By MB1 in forum C++ Programming
    Replies: 6
    Last Post: 11-03-2005, 01:48 PM
  5. VC++ Debugging
    By neandrake in forum C++ Programming
    Replies: 5
    Last Post: 12-02-2003, 07:31 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21