473,785 Members | 2,506 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc and memory leaks

cs
This is the function malloc_m() that should be like malloc() but it
should find memory leak, and over bound writing in arrays.

How many errors do you see?
Thank you
*************** *************** **************
/* mallocm.c */
/* funzione di libreria per trattamento della memoria e rilevamento
errori */
/* uso: c_compiler malloc.c e usare malloc .obj */
/*
Declino ogni responsabilita' per qualsiasi danno
che potrebbe arrecare questo programma e ogni
garanzia che serva a qualche cosa; Il programma si
intende libero (free) per l'uso e per il
cambiamento.

*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* MEM_LIMIT e' il limite del numero di diversi puntatori
ritornati da malloc_m */
#define MEM_LIMIT 100000
#define MAX_ARRAYS 255
#define UNS unsigned

/*************** **********CCCCC CC************* *************** ******/
#ifdef __cplusplus
extern "C" {
#endif

static unsigned yuyuy=0;
typedef double Align; /* per allineare alla double */

union header { /* header del blocco */
struct {union header* ptr; /* blocco successivo in free list */
unsigned size; /* dimensione di questo blocco */
}s;
Align x; /* forza l'allineamento dei blocchi */
};

typedef union header Header;
static Header base; /* lista vuota per iniziare */
static Header *freep=NULL; /* inizio della free list */

char name_ [ 1100 ] = {0}; /* name_== nome routines chiamate
*/
char memo_ [ 300 ] = {0}; /* stringa ove errori trovati in
memoria */
int n_i_ = 0 ;
int libero_m_ = 0 ; /* libero_m_==1 controllo tutti i
vettori a
ogni chiamate di free(); serve insieme a name_ per individuare le
routines che
sovrascrivono la memoria che non hanno (e.g. if(libero_m_)
init_w("nome_ro utines");) */

typedef struct {
void *p;
unsigned size;
unsigned piu;
unsigned meno;
}vettore_array;

static vettore_array **p_p_p_=0; /* lista di struct di puntatori
ritornati da malloc_m */
static unsigned i_i_i_=0; /* attuale indice nella lista */
static unsigned m_m_m_=0; /* massimo indice nella lista */
static char **list_ =0; /* lista dei vettori richiesti al
sys */
static unsigned list_i_=0;
static unsigned list_m_=0;
static int mem_init(unsign ed siz)
{vettore_array **pp;
unsigned j;
/*---------------------*/
//printf("p_p_p_= %p i_i_i_==%u siz=%u ", (void*) p_p_p_, i_i_i_,
siz );
if(p_p_p_==0)
{pp= (vettore_array* *) malloc( (siz+1) * sizeof *pp );
if(pp==0) return 0;
for( j=0; j<siz; ++j)
{pp[j]= (vettore_array* ) malloc( sizeof(vettore_ array) );
if(pp[j]==0)
{if(j!=0)
for( --j ; j!=0 ; --j)
free( (void*) pp[j] );
free((void*) pp[0]); free((void*) pp); return 0;
}
}
}
else { if(siz==m_m_m_) return 1;
else if(siz < m_m_m_) /* dovrebbe distruggere la
memoria eccessiva */
{ if(siz<=i_i_i_) return 1; /* la 1024ma volta che viene
chiamato free_m()*/
for(j=siz; j<m_m_m_; ++j) // v[0]...v[size]=size+1
free((void*) p_p_p_[j]);
pp=(vettore_arr ay**) realloc(p_p_p_, (siz + 1) * sizeof
*pp );
if(pp==0) {printf("Fallim ento realloc\n"); m_m_m_ =
siz; return 1;}
/* ritorna senza cambiare niente */
goto label;
}
pp= (vettore_array* *) realloc( (void*) p_p_p_, (siz + 1) *
sizeof *pp);
if(pp==0) {printf("Fallim ento realloc\n"); return 0;}
if( siz > i_i_i_)
{ for( j=i_i_i_; j<siz; ++j)
{pp[j]= (vettore_array* ) malloc(
sizeof(vettore_ array) );
if(pp[j]==0)
{if(j!=0)
for( --j ; j!=0 ; --j)
free( (void*) pp[j] );
free((void*) pp[0]); return 0;
}

}
}
}
label: ;
m_m_m_ = siz; p_p_p_=pp; return 1;
}

/* malloc_m: allocatore di memoria */
void* malloc_m(unsign ed nbytes)
{Header *p, *prevp;
unsigned nunits, *k, *kk, led, size;
Header* morecore(unsign ed);
unsigned verifica_all_m( void );
void stato_mem(void) ;
/*-------------------------------*/
if(libero_m_)
{
if(verifica_all _m()==0)
stato_mem();
}
if(i_i_i_>MEM_L IMIT || nbytes==0 ) return 0;
if(i_i_i_>=m_m_ m_)
{if(mem_init( i_i_i_ + MAX_ARRAYS ) == 0) return 0;}
nunits = nbytes + sizeof(Header);
nunits = nunits/sizeof(Header) + (( nunits%sizeof(H eader)
sizeof(unsigne d) ) ? 1: 0) + 1;

if((prevp=freep )==NULL) /* non esiste la free list */
{ base.s.ptr=free p=prevp=&base; base.s.size=0; }
for(p=prevp->s.ptr; ; prevp=p, p=p->s.ptr)
{if(p->s.size>=nunits ) /* spazio insufficiente */
{if(p->s.size==nunits ) /* esattamente */
{
prevp->s.ptr = p->s.ptr;
}
else /* alloca la parte finale */
{
p->s.size -= nunits;
p += p->s.size;
p->s.size =nunits;
}
freep = prevp;
/*************** *** Blocco aggiunto ************/
size = nbytes;
led = (size % sizeof(unsigned )!=0) ? 1: 0;
k = (unsigned*)(p+1 ); kk=k; --k;
p_p_p_[i_i_i_]->meno = *k;
p_p_p_[i_i_i_]->piu = kk[size/sizeof(unsigned )+ led];
p_p_p_[i_i_i_]->size = size;
p_p_p_[i_i_i_++]->p = (void*)(p+1);
/*************** *************** *************** **/
return (void*) (p+1);
}
if(p==freep) /* la free list e' terminata */
{++yuyuy; /* numero delle volte di mem.
richieste al sistema */
if((p=morecore( nunits)) == NULL)
return NULL; /* non c'e' piu' spazio */
}
}
}

/* Ritorna il numero degli elementi;
se il numero degli elementi e' 0 ritorna (unsigned) -1
se errori ritorna 0 */
unsigned verifica_all_m( void )
{unsigned j, *k, *kk, xk, xkk, led;
/*----------------*/
if( p_p_p_==0 || i_i_i_==0 ) return -1;
for(j=0 ; j < i_i_i_ ; ++j)
{k = (unsigned*) (p_p_p_[j]->p); kk=k; --k;
led = (p_p_p_[j]->size % sizeof(unsigned )!=0) ? 1: 0;
if( (xk=kk[p_p_p_[j]->size/sizeof(unsigned ) + led]) !=
(xkk=p_p_p_[j]->piu) )
{

/* nota bene: n:v significa NUOVO VALORE : VECCHIO VALORE */

sprintf(memo_ , "verifica_all_m MEM_+ p=%5p size=%5u p[-1]=%5u
p[max]=%5u n:v=%5u:%5u",
p_p_p_[j]->p, p_p_p_[j]->size, p_p_p_[j]->meno,
xkk, xk, xkk);

if(n_i_>2) name_[ n_i_ - 2 ]='+';
return 0;
}
if( (xk=*k) != (xkk=p_p_p_[j]->meno) )
{ sprintf(memo_ , "verifica_all_m MEM_- p=%5p size=%5u
p[-1]=%5u p[max]=%5u n:v=%5u:%5u",
p_p_p_[j]->p, p_p_p_[j]->size, xkk,
p_p_p_[j]->piu, xk, xkk);
if(n_i_>2) name_[n_i_ - 2]='-';
return 0;
}
}
return i_i_i_;
}

void verifica_all( void )
{if(verifica_al l_m( )==0)
{printf("Errore nella memoria\n");
printf("memo=%s name=%s\n", memo_, name_ );
}
}

/* ritorna 0 se il vettore fa parte della lista
se pointer==0 ritorna 1 se tutto e' cancellato
2 se tutto e' cancellato tranne il puntatore iniziale
3 altrimenti
*/
unsigned verifica_m( void* pointer, unsigned *jj)
{unsigned j, *k, *kk, xk, xkk, led;
/*----------------*/
if(jj!=0) *jj=0;
if(pointer==0)
{if( i_i_i_==0 && p_p_p_==0 ) return 1;
else if(i_i_i_==0) return 2;
else return 3;
}
if(p_p_p_==0 ) return 1;
for(j=0 ; j < i_i_i_ ; ++j)
if( p_p_p_[j]->p == pointer ) break;
if(j==i_i_i_ ) {printf("verifi ca_mMEM_0 %p indice=%u memo=%s
name=%s\n", pointer, i_i_i_, memo_, name_ );
if(n_i_>2) name_[n_i_ -2]='0'; return 7;
}
k = (unsigned*) pointer; kk=k; --k;
led = (p_p_p_[j]->size % sizeof(unsigned )!=0) ? 1: 0;
*jj=j;
if( (xk=kk[p_p_p_[j]->size/sizeof(unsigned ) + led]) !=
(xkk=p_p_p_[j]->piu) )
{ printf("p=%p size=%u p[-1]=%u p[max]=%u ", pointer,
p_p_p_[j]->size, *k, xk);
printf("verific a_mMEM_+ n:v>%u:%u\n", xk, xkk);
if(n_i_>2) name_[ n_i_ - 2 ]='+';
return 8;
}
if( (xk=*k) != (xkk=p_p_p_[j]->meno) )
{ printf("p=%p size=%u p[-1]=%u p[max]=%u ", pointer,
p_p_p_[j]->size, xkk, p_p_p_[j]->piu);
printf("verific a_mMEM_- n:v>%u:%u\n", xk, xkk);
if(n_i_>2) name_[n_i_ - 2]='-';
return 9;
}
else return 0;
}

unsigned verifica_p_m( void* pointer)
{unsigned jj;
return verifica_m( pointer, &jj);
}

static void free_list_m(voi d)
{while( list_i_ !=0 )
{--list_i_; free(list_[list_i_]);}
free(list_); list_=0; list_m_=0; freep=NULL;
}

static void free_vettore_m( void)
{if(p_p_p_==0) { m_m_m_=0; i_i_i_=0; return;}
while( i_i_i_ !=0 )
{--i_i_i_; free((void*) p_p_p_[i_i_i_]); }
free((void*) p_p_p_);
p_p_p_=0; m_m_m_=0;
}
static void inserisci(void* ap, unsigned jk, unsigned j)
{Header *bp, *p;
static unsigned f_cont=0;
/*-------------------*/
if(jk==0) ++f_cont;
bp = (Header*)ap - 1; /* punta all'header del blocco */
for( p=freep; !(bp>p && bp < p->s.ptr); p=p->s.ptr )
if( p >= p->s.ptr && (bp>p || bp < p->s.ptr) )
break; /* il blocco liberato e'
ad un estremo della lista*/
if(jk) goto label;
/*************** *************** **************/
if(j != i_i_i_ - 1)
{
p_p_p_[j]->p = p_p_p_[i_i_i_ - 1]->p;
p_p_p_[j]->size = p_p_p_[i_i_i_ - 1]->size;
p_p_p_[j]->meno = p_p_p_[i_i_i_ - 1]->meno;
p_p_p_[j]->piu = p_p_p_[i_i_i_ - 1]->piu;
}
p_p_p_[--i_i_i_]->p =0; p_p_p_[i_i_i_]->size=0;
p_p_p_[i_i_i_]->meno=0; p_p_p_[i_i_i_]->piu =0;
if(m_m_m_>1000 && f_cont%1024==0)
mem_init(i_i_i_ +64);
/*************** *************** *************** **/
label:
if(bp+bp->s.size == p->s.ptr)/*lo unisce al blocco dopo*/
{bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
}
else bp->s.ptr=p->s.ptr;

if(p+p->s.size == bp)/* lo unisce al blocco prima*/
{p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
}
else p->s.ptr=bp;

freep = p;
}

void free_all_m(void ) {free_vettore_m (); free_list_m();}

/*Non usare free_all_m() ma free_a_i_m se ci sono oggetti
allocati da costruttori e distruttori del c++
(gli oggetti fuori da una qualsiasi procedura finiscono quando si
chiude
l'ultima istruzione del main) */
void free_a_i_m(void )
{if(i_i_i_==0)
{free_vettore_m (); free_list_m(); printf("MEMORIA DINAMICA
LIBERATA\n"); }
}
#define NALLOC 1024 /* numero minimo di unita' richieste */

/* morecore: chiede al sistema memoria aggiuntiva */
static Header* morecore(unsign ed nu)
{char *cp, **p;
Header *up;
unsigned len;
/*-----------------------*/
if(nu<NALLOC) nu=NALLOC;
cp = (char*) malloc(nu * sizeof(Header)) ;
if( cp==0 ) /* non c'e' piu' spazio */
return NULL;

if(list_i_ <= list_m_ )
{len = (list_m_==0 ? 128: 2*list_m_);
p = (char**) realloc(list_, len * sizeof *p);
if(p==0)
{free(cp); return 0;}
list_ = p;
list_m_ =len;
}
list_[list_i_++]=cp;

up=(Header*) cp;
up->s.size=nu;
inserisci((void *)(up+1), 1, 0);
return freep;
}

/* se pointer!=0 ritorna la size del pointer
ritorna 0 se il pointer non c'e' */
unsigned get_size_m( void* pointer )
{unsigned j;
/*----------------*/
if(pointer==0 || p_p_p_==0) return 0;
for(j=0 ; j < i_i_i_ ; ++j)
if( p_p_p_[j]->p == pointer ) break;
if(j==i_i_i_ ) return 0;
return p_p_p_[j]->size;
}

void init_w(const char *nam)
{unsigned i, j;
/*---------------------*/
if(nam==0) return;
if( n_i_ > 2 )
name_[n_i_ - 1]='|';
if( n_i_ >= 1016 ) // 0..14 carattere 15='|'
n_i_=0;
for(i=n_i_, j=0; j<15 && nam[j]!=0; ++i, ++j)
name_[i]=nam[j];
for( ; j< 15; ++i, ++j)
name_[i]=' ';
name_[i] = '#';
n_i_ += 16;
}

void leggi_mem(void)
{Header *u, *v;
unsigned j;
for( u = freep; u!=0 ; )
{printf("|v=%u s=%u|", (unsigned)u / sizeof(Header), u->s.size );
if(u->s.ptr==freep ) break;
v=u->s.ptr;
if((u + u->s.size) != v)
{j = (UNS)(v-u) - u->s.size;
if(j<123456)
printf("%u", j );
else printf("#");
}
u=v;
}
}
void stato_mem(void)
{unsigned j;
leggi_mem();
fflush(stdout);
printf("\nRAPPO RTO MEMORIA DINAMICA. ");
printf("Memoria richiesta al sistema=%u volte. ", yuyuy);
j=verifica_all_ m();
if(j!=0 && j!=-1) printf("%u vettori allocati con successo\n", j);
else {if(j==0) goto label;
printf("Tutto bene. ");
j=verifica_m(0, 0);
if(j==1) printf("Sia la base sia il contatore sono NULLI\n");
else if(j==2) printf("Il contatore e' nullo ma la base no\n");
else {label: ;
printf("Errore nella memoria\n");
printf("memo=%s name=%s\n", memo_, name_ );
free_vettore_m( ); free_list_m();
exit(0);
}
}
}

void controlla_m(cha r* st)
{printf("!%s!", st);
fflush(stdout);
if(verifica_all _m()==0)
{if(st) printf("ERRORE! ");
fflush(stdout);
stato_mem();
}
}
/* free: inserisce in free list il blocco ap */
void free_m(void* ap)
{ unsigned j;
/*-------------------*/
if(ap==0) return ;
if(libero_m_)
{
if(verifica_all _m()==0)
stato_mem();
}
if(verifica_m(a p, &j))
{ printf("free_m( ): "); stato_mem();
free_vettore_m( ); free_list_m();
exit(0);
}
inserisci(ap, 0, j);
}

void stampa_chiamate (void){printf(" memo=%s name=%s\n", memo_, name_
);}

#ifdef __cplusplus
}
#endif
// fine di extern C
/*************** **********CCCCC CC************* *************** ******/
/* file.c che utilizza malloc_m()
c_compiler file.c mallocm.obj */
#include <stdio.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
void* malloc_m(unsign ed nbytes);
unsigned verifica_all_m( void );
unsigned verifica_m( void* pointer, unsigned *jj);
unsigned verifica_p_m( void* pointer);

void free_m(void* ap);
void free_all_m(void );
void free_a_i_m(void );
unsigned get_size_m( void* pointer );
void stato_mem(void) ;
void leggi_mem(void) ;
void controlla_m(cha r* st);
void verifica_all( void );
void init_w(const char *nam);
void stampa_chiamate (void);
#ifdef __cplusplus
}
#endif

extern int libero_m_ ;

void g(void)
{char *r;
/*************** *******/
if(libero_m_) init_w("g() ");
r=malloc_m(100* sizeof(*r));
r[-1]='8'; /* errore per r[-1] */
/* errore non liberato r */
// free_m(r);
/* errore se non uso free_m(r) ed stato_mem() in main mi dice
"RAPPORTO MEMORIA DINAMICA. Memoria richiesta al sistema=1 volte.
1 vettori allocati con successo "
significa che mi sono dimenticato di cancellare un vettore
*/
}

void f(void)
{char *p;
int i;
/*************** ******/
if(libero_m_) init_w("f() ");
p=malloc_m(100* sizeof(*p));
for(i=0; i<110; ++i) p[i]='0'; /* errore per i>=100 */
free_m(p); /* se libero_m_ = 1; identifica routine dell'errore */
/* se libero_m_ = 0; (default) identifica un errore */
g();
}
int main(void)
{// libero_m_ = 1; // scrive routines ove e' identificato l'errore
// se si identifica errore => "libero_m_ = 1;"
// nel codice normale ove non si identificano errori *non* si
// deve scrivere "libero_m_ = 1;"
if(libero_m_) init_w("main");

f();

stato_mem(); /* identifica eventuali errori e "momory leaks"*/
free_all_m(); /* si deve usare prima di uscire dal programma */
stato_mem(); /* se succede
"RAPPORTO MEMORIA DINAMICA. Memoria richiesta al sistema=1 volte.
Tutto bene. Sia
la base sia il contatore sono NULLI"
tutto sembra ok */
return 0;
}

Nov 15 '05
18 3319

"Walter Roberson" <ro******@ibd.n rc-cnrc.gc.ca> wrote in message
news:da******** **@canopus.cc.u manitoba.ca...
In article <f_************ *****@newssvr11 .news.prodigy.c om>,
Robert Redelmeier <re****@ev1.net .invalid> wrote:
In alt.lang.asm Walter Roberson <ro******@ibd.n rc-cnrc.gc.ca> wrote:
:1) Italian language code posted to English language newsgroups
Where??
Comments and variable names.


Comments and variable names are not "English language newsgroups".

comp.lang.c and alt.lang.asm are not "English language newsgroups" either,
merely newsgroups in which English is by far the most common language.

At most it is a Quality of Implementation matter.

The error is in expecting much feedback.


And you know the posters internal mental state at the time of
posting through what mechanism?

I didn't see anything in the original posting indicating that the
original poster expected more than one response.
--
Any sufficiently old bug becomes a feature.


I smile at your close. It is certainly fun to fix a bug and find some
programmer depended on the bug for years.
Nov 15 '05 #11
cs wrote:
i find this relation:
I meant: there is no relation with YOUR code, which is pure C, with NO
assembly, so X-posting to ASM ng would be useless.
But it is possible i'm only a novice or i have get the "wrong way"
the "dark side of the languages" etc
and people as you or Sosman or Betov or Frank or others don't have
this out-of bounds array problems and have not to scan the pc memory
for this.
The problem still remains, writing out of bounds can be always possible.
i'm lazy and i think that people understand the same. it is possible
that there is someone as me, who like to read something in a different
language.


Not in comp.* --- I suggest to be less lazy, especially dealing with
international ngs, which use english by default. It's this way, and you
won't change it.
Nov 15 '05 #12
In alt.lang.asm cs <n@ss.g> wrote:
C routines that use "heap memory" and assembly routines
that use "heap memory" have the same problems: it is easy
(for me at last) goes out of arrays (in writing). where for
"heap memory" i mean the memory returned from malloc-like
functions.


Ah, but there are _no_ malloc()-like functions in ASM!
The programmer has to write their own when they want to
use this feature. Those custom routines tend to be easier
to write because the pgmr knows what they expect it to do,
and don't need to write it to do everything.

If you want to understand malloc() routines, look at how
other languages (pascal?) do it.

Personally, I love segfaults (the error raised when a process
writes on memory it doesn't own -- Sig11). These point out
bug and are _much_ easier to find that trampled memory.
I don't know if the Linux or BSD mmap() syscall permits
mapping isolated pages to give some buffer over-run protection.

-- Robert

Nov 15 '05 #13

"Robert Redelmeier" <re****@ev1.net .invalid> wrote in message
news:BS******** *****@newssvr30 .news.prodigy.c om...


Ah, but there are _no_ malloc()-like functions in ASM!
The programmer has to write their own when they want to
use this feature.
The first sentence and the second sentence are contradictory, of course.

And what's wrong with a programmer using a function that someone else wrote?
Lots of malloc routines *do* exist for assembly language programmers. I've
seen 'em for MASM, HLA, TASM, and just about any other assembler that can
link in an OBJ file.
Those custom routines tend to be easier
to write because the pgmr knows what they expect it to do,
and don't need to write it to do everything.
OTOH, the programmer also has to *know* how to write a good malloc routine.
And contrary to the opinion of many assembly language programmers, getting
it right and keeping performance high, is a challenging task. There have
probably been hundreds of papers published on the subject of memory
allocation, garbage collection, and similar subjects over the past 50 years.

If you want to understand malloc() routines, look at how
other languages (pascal?) do it.
Or read some of those afore-mentioned papers. Don't get the impression that
a particular language's memory allocation routine has "gotten it right",
either. Many C libraries, for example, are known to have pretty bad malloc
routines.

Personally, I love segfaults (the error raised when a process
writes on memory it doesn't own -- Sig11). These point out
bug and are _much_ easier to find that trampled memory.
I don't know if the Linux or BSD mmap() syscall permits
mapping isolated pages to give some buffer over-run protection.


Yes, they do. Though you burn up a whole page to achieve this.
This is one of the advantages of true segmentation vs. flat memory models.
Handling "out of range" errors is much easier in a *true* segmented system
(and 16-bit x86 is *not* true segmentation; to my knowledge, no popular OS
supports 32-bit segmentation).
Cheers,
Randy Hyde
Nov 15 '05 #14
On Sun, 10 Jul 2005 04:11:06 GMT, in comp.lang.c , cs <n@ss.g> wrote:
On Sat, 09 Jul 2005 12:01:48 -0500, Sensei <se******@tin.i t> wrote:
cs wrote:
This is the function malloc_m() that should be like malloc() but it
should find memory leak, and over bound writing in arrays.


Don't cross-post, and especially when no assembly code is present in the
code. That's C with no relations with assembly.


i find this relation:
C routines that use "heap memory" and assembly routines that use "heap
memory" have the same problems:


As quite probably do pascal, fortran, forth and bloody haskell, if any
of those also use heaps. Do you think the solution would be common
too?
Be sensible. C is not assembler.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 15 '05 #15
In alt.lang.asm Randall Hyde <ra*******@eart hlink.net> wrote:
"Robert Redelmeier" <re****@ev1.net .invalid> wrote in message
Ah, but there are _no_ malloc()-like functions in ASM!
The programmer has to write their own when they want to
use this feature.
The first sentence and the second sentence are contradictory, of course.


Well yes. I obviously omitted the word "standard" in the
first sentence. Mea culpa. Mea culpa. Mea maxima culpa!
And what's wrong with a programmer using a function that
someone else wrote? Lots of malloc routines *do* exist for
Sure. But that's not the bare-metal asm way :)

And it isn't as if there's some standard library. 'Course you
can use anything you like, but then you'd better look into
it and see if it really meets your needs. Not like using
the standard libraries that come with compiler languages.
OTOH, the programmer also has to *know* how to write a
good malloc routine.
Only if s/he's going to need or use such a beast.
A FORTRAN programmer won't.
And contrary to the opinion of many assembly language
programmers, getting it right and keeping performance high,
is a challenging task. There have probably been hundreds of
papers published on the subject of memory allocation, garbage
collection, and similar subjects over the past 50 years.
Entirely true. Would you have any good overview URLs
for our OP?

I think it might be good to examine real-world usage
of malloc()'d objects, particularly their persistance.
Yes, they do. Though you burn up a whole page to achieve
Burn one 4 KB page as VM, two as address space including the
guard page. I don't much mind. IMHO, malloc() is for fairly
large variable-length (need guardpage!) objects that have
limited duration. Smalls should be stack locals, and longer
duration should be statics. Fix length should be statics,
potentially a series protected by flags/LRU. KISS.
This is one of the advantages of true segmentation vs. flat
memory models. Handling "out of range" errors is much
easier in a *true* segmented system (and 16-bit x86 is *not*


Understood. But this saves memory at the cost of segment
register loads. You might as well use Pascal-style BOUND
instructions. Cycles are cheap.

-- Robert

Nov 15 '05 #16
"Randall Hyde" <ra*******@eart hlink.net> écrivait news:uffAe.6073 $8f7.2914
@newsread1.news .pas.earthlink. net:
what's wrong with a programmer using a function that someone else wrote?

Nothing... unless it would have been written by... you.

:))
Betov.

< http://rosasm.org >

Nov 15 '05 #17
"Jim Carlock" <an*******@loca lhost.com> wrote:
"Walter Roberson" <ro******@ibd.n rc-cnrc.gc.ca> posted:
comp.lang.c and alt.lang.asm are not
"English language newsgroups"
What's not English about "comp", "lang", "alt" and "asm"?

1) The newsgroup names are English.
2) They start out being hosted in a country where the national
language is English.


Newsgroups are not "hosted". That is not how Usenet works.
3) IF the Italians wanted to host a newsgroup and pay to put the
group upon English servers,
That is not how Usenet works, either.

My news server is Dutch, and it carries groups from it, de, fr, hk and
japan.
5) The newsgroups are pulled by secondary servers in different
countries. The "pulling servers" do NOT provide translation
services for their readers, which is 100% possible,


Bull.

However...

1. The default language on any newsgroup in the Big <whatever the number
is today> is English.

That is the only objection that needed to be made.

Richard
Nov 15 '05 #18
cs
On Sat, 09 Jul 2005 07:19:09 GMT, cs <n@ss.g> wrote:
This is the function malloc_m() that should be like malloc() but it
should find memory leak, and over bound writing in arrays.

How many errors do you see?
Thank you
************** *************** *************** unsigned verifica_m( void* pointer, unsigned *jj)
{unsigned j, *k, *kk, xk, xkk, led;
/*----------------*/
if(jj!=0) *jj=0;
if(pointer==0)
{if( i_i_i_==0 && p_p_p_==0 ) return 1;
else if(i_i_i_==0) return 2;
else return 3;
}
if(p_p_p_==0 ) return 1;
for(j=0 ; j < i_i_i_ ; ++j)
if( p_p_p_[j]->p == pointer ) break;
for(j=i_i_i_-1 ; ; --j )
{if( p_p_p_[j]->p == pointer ) break;
if(j==0) {j=i_i_i_; break;}
}

because it seems to me that
{type a=malloc_m(123) , b=malloc_m(123) ;
operations;
free_m(b); free_m(a);
}
is very common (functions etc)
and this mean for free one pointer in the list of pointer it is only
O(1)
if(j==i_i_i_ ) {printf("verifi ca_mMEM_0 %p indice=%u memo=%s
name=%s\n", pointer, i_i_i_, memo_, name_ );
if(n_i_>2) name_[n_i_ -2]='0'; return 7;
} [...]static void inserisci(void* ap, unsigned jk, unsigned j)
{Header *bp, *p;
static unsigned f_cont=0;
/*-------------------*/
if(jk==0) ++f_cont;
bp = (Header*)ap - 1; /* punta all'header del blocco */
for( p=freep; !(bp>p && bp < p->s.ptr); p=p->s.ptr )
if( p >= p->s.ptr && (bp>p || bp < p->s.ptr) )
break; /* il blocco liberato e'
ad un estremo della lista*/


i don't know here if it is better to begin to end and to go backwards
(like above here)

something like

typedef double Align; /* per allineare alla double */

union header { /* header del blocco */
struct {union header* ptr; /* blocco successivo in free list */
union header* ptb; /* blocco precedente in free list */
unsigned size; /* dimensione di questo blocco */
}s;
Align x; /* forza l'allineamento dei blocchi */
};

typedef union header Header;
static Header base; /* lista vuota per iniziare */
static Header *freep = NULL; /* inizio della free list */
static Header *the_latest = NULL;

and to go from the_latest or from freep pointer backwards in the list
Nov 15 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
7299
by: John | last post by:
In the course of an assignment, I learned the hard way that I shouldn't try to free a malloc'd member of a malloc'd structure after having freed that structure (i.e., free( structure ); free( structure->bufferspace ) ). My question is, if I free just the structure, will the (e.g.) bufferspace be freed implicitly, or do I have to (as I currently am) free the members first? Thanks. -cjl
50
2871
by: Joseph Casey | last post by:
Greetings. I have read that the mistake of calling free(some_ptr) twice on malloc(some_data) can cause program malfunction. Why is this? With thanks. Joseph Casey.
27
1939
by: ncf | last post by:
Hi all. In another topic, I was informed that I had to dynamically allocate memory instead of just trying to expand on a list. (I'm trying to learn C, and have a strong background in PHP and Python) In light of that, I have been trying to learn malloc, realloc, and free, but to no avail. But for some reason, I'm getting segfaults right and left, and to be honest, I am not having any luck at all really in finding out why it isn't...
9
1765
by: questions? | last post by:
if I use malloc() in a function to allocate a space for my array of structures. I didn't free() them anywhere in the program. I found that I can still use that space after I come back to main(). Am I supposed to use that space or it is temporary and will be removed soon afterwards? Thanks
41
3353
by: jacob navia | last post by:
In the C tutorial for lcc-win32, I have a small chapter about a debugging implementation of malloc. Here is the code, and the explanations that go with it. I would appreciate your feedback both about the code and the associated explanations. ---------------------------------------------------------------------
14
12210
by: Bhaskar | last post by:
Hey can any one tell me what malloc 0 does, it assigns space in memory i know that but is it usable and how many bytes does it allocate , allocation of 0 bytes is difficult-to-digest concept and still in the memory.
5
2257
by: FireHead | last post by:
Hello All, Its hard to explain but here it goes: char &free_malloc(char* object_copy){ Here ------------------------------------------------------------------ object_copy is parametre were the contents of the malloc object in main driver module is copied. Which would mean that if I free the object_copy it should not effect
6
1599
by: dade | last post by:
Hi, i use a dynamic 3D matrix of structure that yields to a 90Mb of RAM allocated. To do that i use new operator. here a portion of code struct SInfo { int i1; int i2;
40
540
by: ramu | last post by:
Hi, what happens when i run the below code? main() { int *p; while(1) p= (int *)malloc(1000); } Do i get segmentation fault?
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10161
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10098
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,...
0
8986
agi2029
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...
1
7506
isladogs
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...
0
5390
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...
0
5523
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4058
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
2
3662
muto222
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.