473,695 Members | 2,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dinamic Array Allocation problems

14 New Member
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(__lib c_malloc+0x95)[0xb7e8f9c5]
/lib/tls/i686/cmov/libc.so.6(__lib c_start_main+0x e5)[0xb7e32775]

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:

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

thanks for you help, and sorry for my eng...
Jun 28 '09 #1
25 6484
2,426 Recognized Expert Top Contributor
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.
Jun 29 '09 #2
14 New Member
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...
Jun 29 '09 #3
14 New Member
it does't work.... and for the segmentation fault problem?
Jun 29 '09 #4
2,426 Recognized Expert Top Contributor
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.
Jun 29 '09 #5
14 New Member
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...
Jun 29 '09 #6
11,448 Recognized Expert MVP
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,

Jun 29 '09 #7
2,426 Recognized Expert Top Contributor
Expand|Select|Wrap|Line Numbers
  1. int *VerificaDimezzamento(int array[], int n, int *d)
  2.    {
  3.    int *b, i;
  4.    if(n<=(*d)/4)
  5.       {
  6.       b=malloc(((*d)/4)*sizeof(int));
  7.       for(i=0; i<n;i++) 
  8.          b[i]=array[i];
  9.       for(;i<((*d)/4);i++)
  10.          b[i]=0;
  11.       *d=2*(*d);
  12.       return b;
  13.       }
  14.    return array;
  15.    }
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.

Expand|Select|Wrap|Line Numbers
  1. typedef struct el {int *array; int n; int d; struct el *succ;} elemento;
  2. ...
  3. elemento pop(pile *pila)
  4.    {
  5.    elemento a;
  6.    pile tmp;
  7.    if(pila!=NULL)
  8.       {
  9.       a=**pila;
  10.       tmp=*pila;
  11.       *pila=(*pila)->succ;
  12.       return a;
  13.       }
  14.    else 
  15.       {
  16.       printf("pila vuota!"); 
  17.       return a;
  18.       }
  19. }
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.
Jun 29 '09 #8
14 New Member
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) {
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
Jun 29 '09 #9
2,426 Recognized Expert Top Contributor
Please use CODE tags. The following code snippet is much easier to read:
Expand|Select|Wrap|Line Numbers
  1. elemento pop(pile *pila)
  2.    {
  3.    elemento a;
  4.    pile tmp;
  5.    if(*pila!=NULL)
  6.       {
  7.       a=**pila;
  8.       tmp=*pila;
  9.       *pila=(*pila)->succ;
  10.       return a;
  11.       }
  12.    else 
  13.       {
  14.       printf("pila vuota!"); 
  15.       exit(1);
  16.       }
  17.    }
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.
Jun 29 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Roberto Dias | last post by:
I'm a newbie in C++ programming. I bought a book yet and I have learned by means internet donwloadble materials. I feel not confortable using multi-dimensional arrays. I simply cannot understand memory allocation principle. I have got some ideas that require this one, but only thoughts and no action I have done. Unfortunately, the Deitel book don't explore this topic well. Vectors? How to use them insted of multi-dimensional arrays? What...
by: masood.iqbal | last post by:
I am having lots of trouble getting a simple program that initializs a dynamically allocated 2D array to work. My 2D array is not getting initialized properly, and additionally I am getting a "Null pointer assignment" error. Kindly help. Also, eventually I intend to move this logic to a separate function. For that, I believe, that I will need to pass a pointer-to-pointer-to-pointer type as an arguent. Please confirm.
by: gp | last post by:
Hi all, I'm using Microsoft Visual C++ 6.0, I would like to see, debugging my project, all the elements of my dinamic objects.... I have a dinamic array and a STL vector and I need to know the fields values at a specific position, but in the Watch windows I can only see the first element...
by: Vamsee | last post by:
I have a 4D array: float T; ( have to go atleast upto T if system supports) How to malloc() it? can you please give me a brief illustration because I haven't found any article dealing with this. if I say
by: Morgan | last post by:
I have read much posts on the argument but no one clearly says if this operation is possible or not. Simply I have a routine which reads from a text file some integer arrays (1 or 2D). The first array in the file has known dimension, but it contains the dimensions (so unknown at compile time) of all the other arrays. So I can allocate memory only after reading the
by: Simon Schaap | last post by:
Hello, I have encountered a strange problem and I hope you can help me to understand it. What I want to do is to pass an array of chars to a function that will split it up (on every location where a * occurs in the string). This split function should allocate a 2D array of chars and put the split results in different rows. The listing below shows how I started to work on this. To keep the program simple and help focus the program the...
by: Jake Thompson | last post by:
Hello I have the following defined structure struct cm8linkstruc { char *type; /* type of item*/ char *desc; /* description of item */ char *item_increment; /* increment value for item in folder */
by: javuchi | last post by:
I just want to share some code with you, and have some comments and improvements if you want. This header file allocates and add and delete items of any kind of data from a very fast array: #include <stdlib.h> #ifndef __LIST_H__ #define __LIST_H__
by: Silas Silva | last post by:
Hello all! I'm learning C and I started to get into malloc() and va_* functions of stdarg.h (va_list, va_arg, va_start, etc). So I wrote the following program that has a funcion that concatenates strings: /********** START ***********/ #include <stdarg.h> #include <stdio.h> #include <string.h>
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.