Dinamic Array Allocation problems

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stararic
    New Member
    • Jun 2009
    • 14

    Dinamic Array Allocation problems

    hi, I'm writing a program a kind of calculator that should work with very big numbers (thousand of digits). So, numbers are rappresented by a struct that contains a pointer to integer, e 2 int for dimension of the array e number of digits.
    the pointer is than used for the malloc of the array...
    my 2 problems are:

    1)some time, when I use my exp function I get the error:

    *** glibc detected *** ./a.out: free(): invalid size: 0x0975a328 ***
    ======= Backtrace: =========
    /lib/tls/i686/cmov/libc.so.6[0xb7e8b604]
    /lib/tls/i686/cmov/libc.so.6[0xb7e8eabc]
    /lib/tls/i686/cmov/libc.so.6(__lib c_malloc+0x95)[0xb7e8f9c5]
    ./a.out[0x804a8ab]
    ./a.out[0x804bb52]
    ./a.out[0x804ba3d]
    ./a.out[0x804ba3d]
    ./a.out[0x804ba3d]
    ./a.out[0x804ba3d]
    ./a.out[0x804ba3d]
    ./a.out[0x804ba3d]
    ./a.out[0x8049e32]
    ./a.out[0x8048892]
    /lib/tls/i686/cmov/libc.so.6(__lib c_start_main+0x e5)[0xb7e32775]
    ./a.out[0x8048401]

    and other stuff... can It be becouse it is a recursive function?

    the second and biggest problem is that when the number becomes too large (something like 1000 digits) I get a segmentation fault... there are strange problems with arrays of this dimension?

    the code is very big but you can find it at:
    Download the latest 7-Zip for Windows 11. Free、fast、secure download. Easy installation, top compression. Your go-to 7zip solution


    ps: I've deleted the free() functions... It caused too many errors...

    thanks for you help, and sorry for my eng...
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Are you using malloc (or calloc) to dynamically allocate memory; and free to release dynamically allocated memory?

    If so, are you trapping the exceptional case when malloc/calloc return an error because there is no available memory to allocate? If not, then you need to do so.

    The "free(): invalid size: 0x0975a328" message sounds like you are trying to free a block of memory that wasn't dynamically allocated. This could happen if you free the same block twice; or if the pointer argument gets corrupted somewhere between being returned by malloc and being passed back to free.

    Dynamic memory allocation works fine with recursive functions ... provided that you don't run out of memory. You want to be careful to free memory as soon as it isn't needed.

    A general problem is memory fragmentation -- when the pattern of free's doesn't match the pattern of malloc's, so small freed blocks are not contiguous, leading eventually to the circumstance where malloc for a large block fails (despite there being more than enough memory) because no portion of free heap space is large enough to satisfy the request.

    Comment

    • stararic
      New Member
      • Jun 2009
      • 14

      #3
      thanks for the reply, I don't use free and I'm not trapping that case... how to do it? something like:
      a=malloc(d*size of(int));
      if(a==NULL) {printf("error" ); exit(1);}

      does it works? I will try this afternoon...

      Comment

      • stararic
        New Member
        • Jun 2009
        • 14

        #4
        it does't work.... and for the segmentation fault problem?

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          So ... I gather from your terse response that you added the error traps to all malloc/calloc/realloc function calls; and that none of the traps were taken; and that the program continues to fail as it did before -- with a run-time segmentation fault.

          "Segmentati on fault" means that you tried to access nonexistent memory. The most common ways to do this include:
          • dereferencing a NULL pointer;
          • dereferencing a pointer into dynamic memory after the memory has been freed;
          • dereferencing a corrupted pointer;
          • accessing past the end of a dynamic memory block, typically by using a too-large array index.


          1. Examine the segmentation fault error message. It should report the address where the fault occurred. Compare that address to your link map to see which function contains the offending instruction. Presumably the offending instruction dereferences a pointer into one of your allocated memory blocks. Look carefully to make sure that pointer does indeed point into a valid memory block. Also look carefully to make sure you're not accessing past the end of that block (for instance, with a too-large array index).

          2. I notice your backtrace was almost all raw hexadecimal addresses. Temporarily make all of your functions global (by removing "static" keyword). See if that induces the backtrace to report function names.

          I will try to look at your source code, but it may be quite awhile before I have time to work through such a large source file. It would help if you provided the segmentation fault backtrace, decoding the hex addresses into function names.

          Comment

          • stararic
            New Member
            • Jun 2009
            • 14

            #6
            sorry for newbie question... but when you say "link map" what does it means??
            and I don't know what is a global function and what is not, so maybe are all global... I will post the code again with the add you said.
            however, I've 2 kind of errors... this one:
            free(): invalid size: 0x0975a328
            caused by the exp function (espone in the code), and the second one, that say just "segmentati on fault" when the number of digits is >1000...

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #7
              Originally posted by stararic
              I've 2 kind of errors... this one:
              free(): invalid size: 0x0975a328
              caused by the exp function (espone in the code), and the second one, that say just "segmentati on fault" when the number of digits is >1000...
              The 'invalid size' error most likely originates from corrupted memory or a pointer value you're trying to free() that you haven't malloc()'d. A segmentation fault most likely originates from corrupted memory or buffer overflows.

              kind regards,

              Jos

              Comment

              • donbock
                Recognized Expert Top Contributor
                • Mar 2008
                • 2427

                #8
                Code:
                int *VerificaDimezzamento(int array[], int n, int *d)
                   {
                   int *b, i;
                   if(n<=(*d)/4)
                      {
                      b=malloc(((*d)/4)*sizeof(int));
                      for(i=0; i<n;i++) 
                         b[i]=array[i];
                      for(;i<((*d)/4);i++)
                         b[i]=0;
                      *d=2*(*d);
                      return b;
                      }
                   return array;
                   }
                I don't understand what this function is trying to do; but I notice that the size of the memory allocation is (*d)/4 times sizeof(int), but it sets *d to 2*(*d). That difference between the size of the allocation and the new value of *d contrasts with VerificaRaddopp io.


                Code:
                typedef struct el {int *array; int n; int d; struct el *succ;} elemento;
                ...
                elemento pop(pile *pila)
                   {
                   elemento a;
                   pile tmp;
                   if(pila!=NULL)
                      {
                      a=**pila;
                      tmp=*pila;
                      *pila=(*pila)->succ;
                      return a;
                      }
                   else 
                      {
                      printf("pila vuota!"); 
                      return a;
                      }
                }
                Are you sure that *pila is never NULL (like if the pile is empty)? If it is ever NULL then the line 'a=**pila' will provoke a segmentation fault.

                If pila is NULL then this function returns an uninitialized elemento without any warning to the caller. In that case, there will probably be a segmentation fault if the caller tries to dereference the array or succ fields of the uninitialized elemento.


                I haven't gone very far into this source file yet.

                In general, this code makes little attempt to verify that pointers aren't NULL before dereferencing them. It is good practice to get in the habit of always checking pointers. This may result in some unnecessary checks, but it may save you many months of unnecessary debugging over the extent of your programming career.

                By the way, you would be doing yourself a favor by adding some comments to this program.

                Forget about my earlier suggestion to make the functions global.

                Comment

                • stararic
                  New Member
                  • Jun 2009
                  • 14

                  #9
                  thaks, for first one "VerificaDimezz amento", I never use it, so I I have removed it. the second one "pop" is now:
                  elemento pop(pile *pila)
                  {elemento a;pile tmp;
                  if(*pila!=NULL) {
                  a=**pila;
                  tmp=*pila;
                  *pila=(*pila)->succ;
                  return a;}
                  else {printf("pila vuota!"); exit(1);}
                  }

                  I'm adding some things to the code, I will post it soon. I know about the comments:D

                  Comment

                  • donbock
                    Recognized Expert Top Contributor
                    • Mar 2008
                    • 2427

                    #10
                    Originally posted by stararic
                    thaks, for first one "VerificaDimezz amento", I never use it, so I I have removed it. the second one "pop" is now:
                    elemento pop(pile *pila)
                    {elemento a;pile tmp;
                    if(*pila!=NULL) {
                    a=**pila;
                    tmp=*pila;
                    *pila=(*pila)->succ;
                    return a;}
                    else {printf("pila vuota!"); exit(1);}
                    }

                    I'm adding some things to the code, I will post it soon. I know about the comments:D
                    Please use CODE tags. The following code snippet is much easier to read:
                    Code:
                    elemento pop(pile *pila)
                       {
                       elemento a;
                       pile tmp;
                       if(*pila!=NULL)
                          {
                          a=**pila;
                          tmp=*pila;
                          *pila=(*pila)->succ;
                          return a;
                          }
                       else 
                          {
                          printf("pila vuota!"); 
                          exit(1);
                          }
                       }
                    By the way, you should still confirm that pila is not NULL before dereferencing it. Why is tmp there if you don't use it? Now that you have removed elemento 'a' from the pile, you don't want anybody to use a.succ to peek into the pile -- it is good linked-list hygiene to set a.succ to NULL before returning 'a'.

                    By the way, with all the 'free' calls removed this program is one huge memory leak -- especially the recursive functions. That isn't causing your current problems (as long as malloc returns successfully), but should be fixed before you consider your program done.

                    Comment

                    • stararic
                      New Member
                      • Jun 2009
                      • 14

                      #11
                      Code:
                      elemento pop(pile *pila)
                      {elemento a;pile tmp;
                      	if(*pila!=NULL){
                      		a=**pila;
                      		*pila=(*pila)->succ;
                      a.succ=NULL;
                      		return a;}
                      		else {printf("pila vuota!"); exit(1);}
                      }
                      that's ok??

                      Comment

                      • donbock
                        Recognized Expert Top Contributor
                        • Mar 2008
                        • 2427

                        #12
                        That's good, but you should check if pila is NULL before you dereference it to check if *pila is NULL.

                        Whenever you see a pointer being dereferenced with '*' you should ask yourself if there is any chance for that pointer to be NULL.

                        Whenever you see a pointer being dereferenced with '->' you should ask yourself if there is any chance for that pointer to be NULL.

                        Comment

                        • stararic
                          New Member
                          • Jun 2009
                          • 14

                          #13
                          uhm understood... now the code is here:
                          Download the latest 7-Zip for Windows 11. Free、fast、secure download. Easy installation, top compression. Your go-to 7zip solution

                          it still doesn't work... I'm trying to change the use of memory, but I'm not sure I'm doing good becouse there are still a lot of errors... thanks again for you help... Without you I'm in very big trouble, this is a project for an universitary exam...

                          Comment

                          • donbock
                            Recognized Expert Top Contributor
                            • Mar 2008
                            • 2427

                            #14
                            Originally posted by stararic
                            sorry for newbie question... but when you say "link map" what does it means??
                            Typically, there is a compiler option that causes a "link map" to be generated. The link map is a list of all global (that is, not-static) identiifers along with the address of each. You will have to look at your compiler documentation to discover how your specific compiler supports this feature.

                            Comment

                            • donbock
                              Recognized Expert Top Contributor
                              • Mar 2008
                              • 2427

                              #15
                              Originally posted by stararic
                              ...this is a project for an universitary exam...
                              Please post specific questions or complete descriptions of actual compiler or run-time faults. I'm reluctant to provide too much general assistance.

                              Comment

                              Working...