malloc and memory leaks

Discussion in 'C Programming' started by cs, Jul 9, 2005.

  1. cs

    cs Guest

    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

    /*************************CCCCCCC**********************************/
    #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_routines");) */

    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(unsigned 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_array**) realloc(p_p_p_, (siz + 1) * sizeof
    *pp );
    if(pp==0) {printf("Fallimento 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("Fallimento 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(unsigned nbytes)
    {Header *p, *prevp;
    unsigned nunits, *k, *kk, led, size;
    Header* morecore(unsigned);
    unsigned verifica_all_m( void );
    void stato_mem(void);
    /*-------------------------------*/
    if(libero_m_)
    {
    if(verifica_all_m()==0)
    stato_mem();
    }
    if(i_i_i_>MEM_LIMIT || 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(Header)
    >sizeof(unsigned) ) ? 1: 0) + 1;

    if((prevp=freep)==NULL) /* non esiste la free list */
    { base.s.ptr=freep=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_mMEM_+ 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_mMEM_- 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_all_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("verifica_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("verifica_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("verifica_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(void)
    {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(unsigned 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_=nam[j];
    for( ; j< 15; ++i, ++j)
    name_=' ';
    name_ = '#';
    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("\nRAPPORTO 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(char* 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(ap, &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
    /*************************CCCCCCC**********************************/
    /* 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(unsigned 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(char* 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='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;
    }
    cs, Jul 9, 2005
    #1
    1. Advertising

  2. Peter Nilsson, Jul 9, 2005
    #2
    1. Advertising

  3. In alt.lang.asm cs <> wrote:
    > How many errors do you see?


    0) Overlong included text
    1) Italian language code posted to English language newsgroups
    2) No asm code posted to an asm newsgroup. ASM doesn't have
    malloc(), and nor is it a syscall [but a libc fn]

    -- Robert
    Robert Redelmeier, Jul 9, 2005
    #3
  4. In article <t1Sze.2161$>,
    Robert Redelmeier <> wrote:
    :In alt.lang.asm cs <> wrote:
    :> How many errors do you see?

    :1) Italian language code posted to English language newsgroups

    Where??

    comp.lang.c and alt.lang.asm are certainly predominately
    English in their discussions, but they do not have charters
    restricting discussions or variable names or comments to English.

    If someone posts on a topic or in a language that relatively few
    readers understand, then they are not going to receive as much
    feedback as they might otherwise, but that is not an *error*.
    It isn't even any more Undefined Behaviour (UB) than any other posting.
    At most it is a Quality of Implementation matter.

    --
    "I want to make sure [a user] can't get through ... an online
    experience without hitting a Microsoft ad"
    -- Steve Ballmer [Microsoft Chief Executive]
    Walter Roberson, Jul 9, 2005
    #4
  5. In alt.lang.asm Walter Roberson <-cnrc.gc.ca> wrote:
    > :1) Italian language code posted to English language newsgroups
    > Where??


    Comments and variable names.

    > At most it is a Quality of Implementation matter.


    The error is in expecting much feedback.

    -- Robert
    Robert Redelmeier, Jul 9, 2005
    #5
  6. cs

    Sensei Guest

    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.

    Don't use italian language in your code (altrimenti pochi capiscono e
    non ti risponderanno MAI), being that comments, variables or whatever.

    > /* uso: c_compiler malloc.c e usare malloc .obj */


    This is compiler/platform dependent. Just provide code, a ``.obj'' is
    not everywhere in the world.

    > /*
    > 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.
    >
    > */


    Better for you: GPL, BSD, MIT?

    > #define MEM_LIMIT 100000
    > #define MAX_ARRAYS 255


    Where the hell did you get these limits? Just... guessing?

    > #define UNS unsigned


    Useless but harmless.

    > 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 */
    > };


    Why are you aligning at doubles?

    <<Big SNIP>>

    Can you use better names than p_p_p_ and so on?

    > static int mem_init(unsigned siz) [...]


    Some pointers.

    First, google for libraries, there are some.

    Second, the source code contains some weird debug code, I suggest using
    something like:

    /* Uncomment the following line to use debugging info */
    #define DEBUGGING_MALLOC
    ....

    static blah()
    {
    ...
    #ifdef DEBUGGING_MALLOC
    printf("Whatever %s %p %d ...
    #endif
    ...
    }

    You have better code avoiding compilation of useless things when releasing.

    Then... did you use valgrind or other memory leak tools for your code
    safety?
    Sensei, Jul 9, 2005
    #6
  7. In article <f_Sze.2927$>,
    Robert Redelmeier <> wrote:
    >In alt.lang.asm Walter Roberson <-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.
    Walter Roberson, Jul 10, 2005
    #7
  8. cs

    cs Guest

    On Sat, 09 Jul 2005 12:01:48 -0500, Sensei <> 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: 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.

    I would say that this is not true for assembly routines that have
    static memory: these memory problems seems find at once in assembly.
    But if some assembly routine have some "heap" memory the problem
    remain.

    So a function like malloc_m that find *if* and *where* are these
    errors (or most of them) is not only useful but *necessary*.
    I am a very positive experience for use malloc_m with assembly code
    called from c[++] code.

    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.

    >Don't use italian language in your code (altrimenti pochi capiscono e
    >non ti risponderanno MAI), being that comments, variables or whatever.


    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.
    cs, Jul 10, 2005
    #8
  9. cs

    Jim Carlock Guest

    "Walter Roberson" <-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.
    3) IF the Italians wanted to host a newsgroup and pay to put the
    group upon English servers, that's their choice, but they'll more
    than likely want to put them on Italian servers and own the
    servers themselves and provide Italian newsgroup names.
    4) It's polite to put the conversation in the "native language".
    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, but they
    fail to provide the services.
    6) Not only did the OP post C coding into a assembly language
    group, but his comments were in Italian(?). Two strikes...
    where's the third strike? Robert plays one-strike or two-strike
    baseball, and doesn't provide the opportunity for the third-strike?
    Sounds like a better game of baseball. Definitely would shorten
    the game. "Arena" baseball anyone? <g>
    7) Who cares enough to argue about it? Blah! LOL

    In Italian, the newsgroup names might be called:

    it.calc.ling.c
    it.alt.ling.mac or it.alt.ling.calc or it.alt.ling.cerv or it.alt.ling.ec

    alt.lang.asm
    it = Italiano (Italian)
    alt = alternativa (alternate)
    ling = lingua (language)
    mac = macchina (machine)
    cerv = cervello (brain)
    calc = calcolatore (computer)
    ec = elaboratore centrale (mainframe)

    comp.lang.c
    calc = calcolatore (computer)
    ling = lingua (language)
    cod = codificatore (coder)

    --
    Jim Carlock
    Please post replies to newsgroup.
    Jim Carlock, Jul 10, 2005
    #9
  10. In article <a32Ae.149533$>,
    Jim Carlock <> wrote:
    >"Walter Roberson" <-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"?



    >2) They start out being hosted in a country where the national
    >language is English.


    Which country was that?

    comp.lang.c and alt.lang.asm are both renames of older groups.

    comp.lang.c as a name dates from The Big Renaming -- it was
    one of the many news.* newsgroups before that. It immediately had
    a large multinational following in its new name.

    alt.lang.asm is a rename of alt.lang.ml and appears to have
    happened within a matter of days of the creation of alt.lang.ml .
    The very oldest messages in alt.lang.ml appear to have been lost.
    One of the earliest posts that is there is from someone in Mexico;
    the "national language" there isn't English.

    The creator of alt.lang.asm appears to have been at Berkeley California,
    so if you really wanted to stretch the point you could say that it
    "started out" being hosted in the USA, but the newsgroup message
    propogated within hours to other countries, so there is no significant
    history of it being restricted to countries whose national language
    was English.


    >3) IF the Italians wanted to host a newsgroup and pay to put the
    >group upon English servers, that's their choice, but they'll more
    >than likely want to put them on Italian servers and own the
    >servers themselves and provide Italian newsgroup names.


    Is the implication that you "pay" to put some "English" newsgroup on
    Italian servers? I don't think so.


    >4) It's polite to put the conversation in the "native language".


    Perhaps -- but not doing so does not constitute an "error".

    Emperically speaking, politeness is not a significant factor in the
    choice of content posted to comp.lang.c -- and very very briefly
    skimming the past postings of alt.lang.asm, it doesn't appear to
    be a significant factor in alt.lang.asm either.


    >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, but they
    >fail to provide the services.


    So??? Do those secondary servers provide translation services of
    the innumerable flame-fests and OT posts that waste bandwidth in
    the newsgroups?
    --
    Oh, to be a Blobel!
    Walter Roberson, Jul 10, 2005
    #10
  11. cs

    BGreene Guest

    "Walter Roberson" <-cnrc.gc.ca> wrote in message
    news:daplk4$7cu$...
    > In article <f_Sze.2927$>,
    > Robert Redelmeier <> wrote:
    > >In alt.lang.asm Walter Roberson <-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.
    BGreene, Jul 10, 2005
    #11
  12. cs

    Sensei Guest

    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.
    Sensei, Jul 10, 2005
    #12
  13. In alt.lang.asm cs <> 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
    Robert Redelmeier, Jul 10, 2005
    #13
  14. cs

    Randall Hyde Guest

    "Robert Redelmeier" <> wrote in message
    news:BSaAe.18$...


    >
    > 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
    Randall Hyde, Jul 10, 2005
    #14
  15. On Sun, 10 Jul 2005 04:11:06 GMT, in comp.lang.c , cs <> wrote:

    >On Sat, 09 Jul 2005 12:01:48 -0500, Sensei <> 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 =----
    Mark McIntyre, Jul 10, 2005
    #15
  16. In alt.lang.asm Randall Hyde <> wrote:
    > "Robert Redelmeier" <> 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
    Robert Redelmeier, Jul 10, 2005
    #16
  17. cs

    Betov Guest

    "Randall Hyde" <> é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 >
    Betov, Jul 10, 2005
    #17
  18. cs

    Richard Bos Guest

    "Jim Carlock" <> wrote:

    > "Walter Roberson" <-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
    Richard Bos, Jul 11, 2005
    #18
  19. cs

    cs Guest

    On Sat, 09 Jul 2005 07:19:09 GMT, 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.
    >
    >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("verifica_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
    cs, Jul 12, 2005
    #19
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Christine
    Replies:
    0
    Views:
    429
    Christine
    Apr 6, 2004
  2. Replies:
    7
    Views:
    1,119
    Peter Koch Larsen
    Mar 29, 2005
  3. Peter
    Replies:
    34
    Views:
    1,942
    Richard Tobin
    Oct 22, 2004
  4. Gene
    Replies:
    0
    Views:
    448
  5. Replies:
    4
    Views:
    119
Loading...

Share This Page