Thread: Malloc and Automatic variable deallocation

  1. #16
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    What is your function supposed to be doing? Duplicating a string?
    Code:
    char *mystrdup( char *s )
    {
        char * dupe = NULL;
        if( s ) 
        {
            size_t len = 1 + strlen( s );
            dupe = malloc( len );
            if( dupe )
            {
                strcpy( dupe, s );
            }
        }
        return dupe;
    }
    Probably something like that. I see no need to do it all by hand when there are functions to do it for me. However, if for some reason I was required to do it myself with nothing more than malloc...
    Code:
    char *mystrdupe( char *s )
    {
        char *dupe = NULL;
        if( s )
        {
            size_t len = 1;
    
            /* strlen replacement */
            while( *s++ ) len++;
            s -= len;
    
            dupe = malloc( len );
            if( dupe )
            {
                /* strcpy replacement */
                while( len-- )
                    dupe[ len ] = s[ len ];
            }
        }
        return dupe;
    }
    We use the same number of variables here, and lose two function calls. They may not be as optimized as the functions included with the standard library, but they're not too horrible.


    Quzah.
    Last edited by quzah; 08-20-2006 at 12:13 AM. Reason: Removed an unneeded line of code.
    Hope is the first step on the road to disappointment.

  2. #17
    Registered User
    Join Date
    Dec 2004
    Posts
    9

    Problem Solved Stage 1

    <<<< Working CODE >>>>
    Code:
    /*
    Will BE MULTITHREADED
    open a original file (source file)
    Look for the existing custom folder in the HOME directory
    If the HOME directory does not exist
    Then see if the specs exists in the /usr/local/share (Default)
    If the /usr/local/share does not exist then create a template
    create a temp
    */  
    
    #include <cliargs.h>
    
    short get_Stream(FILE* pSource,char* result);
    
    char* get_Copy(char* pStr);
    
    char* get_Copy(char* pStr){
      char *final=0;
      char byte = 0;
      char dummy = 0;
      final = &dummy;
    *final = '\0';
    char *temp=0;temp = pStr;
      //initilize the contents with new address
    do{    byte = *temp;
    	*final = &byte;
    	final++; temp++;
    }while(byte!='\0');
    final++;
    *final='\0';
    temp = 0;
    if(pStr!=NULL){
    temp = pStr;
      final = strcpy(final,temp);}else final="";
      return final;
    }//EOF
    
    short get_Stream(FILE* pSource,char* result){
      size_t buflen = 0; 
      char offset= 0; 
      int ret=EXIT_SUCCESS;
      fpos_t* pCurPos=0 ; //current file position
      fpos_t* pOldPos=0 ; //old file position
      char *finally = 0;
      const char *buffer = 0;
      //get the starting File pointer position
      fgetpos(pSource,&pOldPos); 
      //find the newline  = 0x13
      //0F ==  15
      //0E == 14
      //0D == 13
      //0C == 12
      //0B == 11
      //0A == 10
      do{offset=0;  offset=fgetc(pSource); }
      while(offset!=0x0A && offset!=0x0D && offset!=EOF && offset!=NULL);
      //Are we at end of the file?
      if(offset == EOF || offset==NULL)
        ret= EXIT_FAILURE;
      else{
        //get the Current File position
        fgetpos (pSource,&pCurPos); 
        //Total Buffer Length
        buflen = (size_t)pCurPos - (size_t)pOldPos;    
        if(buflen == EXIT_FAILURE){buflen=buflen+1;ret = EXIT_FAILURE;}
        else{
    	 ret=EXIT_SUCCESS;
          //Reset Everything
          fsetpos (pSource,&pOldPos);    
          //allocate memory for the new address register
          buffer = (const char *)malloc(buflen);
          //read file buffer using fgets
          if(fgets(buffer,buflen,pSource)!=NULL)
          //copy the string to a automatic variable register
         finally = get_Copy(buffer);
          //free the contents
          free(buffer); 
          printf("%s",finally);
       }//ELSE
      }//ELSE
     buffer=0;
      pCurPos = 0;
      pOldPos = 0;   
      return ret;
    }//EOF
      
    int main(int argc,const char* argv[]){
    
      struct FileSettings{
        //  DIR *pFolder;
        FILE* rTmpFile;
        FILE* rSourceFile;
        const char* ATOMIC_NAME;
      };
    
      struct FileSettings *pSetting=0;
        char* ret="";
      pSetting = (struct FileSettings *)malloc(sizeof(struct FileSettings));
    
      pSetting->ATOMIC_NAME = "/home/generic/config.log";
       
      pSetting->rSourceFile = fopen(pSetting->ATOMIC_NAME,"rb");
    
      if(pSetting->rSourceFile==NULL){
          printf("File not found");
        }
      else{
         fseek(pSetting->rSourceFile,SEEK_SET,SEEK_SET);
          while(feof(pSetting->rSourceFile)==EXIT_SUCCESS)
          if(get_Stream(pSetting->rSourceFile,ret)==EXIT_SUCCESS){
          printf("\n");
          }
      }
      fclose(pSetting->rSourceFile);
      free(pSetting);
    }//End of Main Application
    To quazah:
    I do not think you have understood the main purpose of the function get_Copy() have you?

    Stage 2
    Besides all this; in the driver_module in the line:
    How do I make this a reality?
    Code:
       if(get_Stream(pSetting->rSourceFile,ret)==EXIT_SUCCESS){
          printf("\n" ,ret );
          }

  3. #18
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by FireHead
    To quazah:
    I do not think you have understood the main purpose of the function get_Copy() have you?
    No, that's why I asked what it was supposed to do. So are you going to keep us in the dark here, or actually tell us what the ........ it is supposed to do?

    Did you just ignore the first line of my post, or do you have some reason you just don't bother answering questions people ask you? Oh wait, those are all questions, so I can't expect you to actually ........ing answer any of them.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #19
    Registered User
    Join Date
    Dec 2004
    Posts
    9

    Continued......

    Hello All,

    To quazah:
    I think had explained what the get_Copy does and I think gave pseudocode of what the function is supposed to do.

    However:
    I the pseudocode did not make then I will clarify what the program is supposed to.
    get_Stream is a function which a returns a string object that has been read by a file just a like the function BufferedReader :: readLine() in Java.

    get_Copy is called when a object has explicitily been mallocated and returns a new string object which does not depend on mallocated object.

    Hope I made sense.

    Thanks.

  5. #20
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by FireHead
    get_Copy is called when a object has explicitily been mallocated and returns a new string object which does not depend on mallocated object.

    Hope I made sense.

    Thanks.
    Oh, so in other words, you pass it a string, and it duplicates it. Right. I think I've heard of that somewhere before... I just can't remember where.


    Quzah.
    Hope is the first step on the road to disappointment.

  6. #21
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by FireHead
    <<<< Working CODE >>>>
    No, no it isn't. The only reason your program doesn't crash is because you're lucky.
    Quote Originally Posted by FireHead
    Code:
    char* get_Copy(char* pStr)
    {
        char *final=0;
        char byte = 0;
        char dummy = 0;
        final = &dummy; /* Point to a single character. */ 
        *final = '\0';  /* Pointless. dummy is already 0. */ 
        char *temp=0;   /* Mixed declarations. Hope you have a C99 compiler. */ 
        temp = pStr;
    
        //initilize the contents with new address /* No, no it doesn't. */
    do{    byte = *temp; /* Copy one item from 'temp' to  byte. */
    	*final = &byte;  /* Make this 'char' hold an address. Wrong! */
    	final++; temp++; /* Walk 'final' off into no-man's land. */
    }while(byte!='\0');
    final++;
    *final='\0'; /* Nuke whatever the ........ I'm pointing at now... */
    temp = 0;
    if(pStr!=NULL){
    temp = pStr;
      final = strcpy(final,temp);}else final=""; /* ........ing kill whatever I'm pointing at. */
      return final;
    }//EOF /* EOF is "End of File" not "End of Function". There actually is EOF in C. This isn't it. */
    You might think it works, but it most definately does not work.

    Turn on your compiler warnings!


    Quzah.
    Last edited by quzah; 08-20-2006 at 02:24 AM. Reason: Color! + Compiler Warnings are your friend!
    Hope is the first step on the road to disappointment.

  7. #22
    Registered User
    Join Date
    Dec 2004
    Posts
    9

    The compiler never lies....

    Hello,

    I tried a small program example;
    Code:
    int main(int argc,char *argv[]){
    char *source="Hello";
    for(int ptr = 0;source[ptr]!='\0';ptr){
          printf("%c @ %p\n",source[ptr],&source[ptr]);
    }//for
    
    
    
    //my program
    
    source = get_Copy(source);
    for(int ptr = 0;source[ptr]!='\0';ptr){
          printf("%c @ %p\n",source[ptr],&source[ptr]);
    }//for
    
    
    }
    I have not had any issue so far with code.
    Code:
    *final = &byte;  /* Make this 'char' hold an address. Wrong! */
    I disagree with above comment.
    According GCC 4.0.28 I get a warning only the above mentioned code line.

    But if I change it to
    Code:
    *final = (int) &byte ;
    The warning disappears.

  8. #23
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > The warning disappears.
    Yes, you can make the compiler STFU by casting your way out of trouble, but that doesn't make the underlying problem go away.

    If your program cannot compile with
    - maximum warning levels on the compiler, say gcc -W -Wall -ansi -pedantic -O2 prog.c
    - zero casts in the code
    Then you're doing something wrong.

    Oh, and the occasional blank like between blocks of code within a function would greatly aid readability, as would a consistent approach to indentation.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #24
    Registered User
    Join Date
    Dec 2004
    Posts
    9

    continued....

    Even if have the following gcc args
    Code:
    gcc -std=c89 -W -Wall -ansi -pedantic -O2 prog.c
    For the get_Copy function all warnings disappear.

  10. #25
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by FireHead
    I have not had any issue so far with code.
    Good for you. You're still wrong. Your sample program was completely irrelevant to this discussion.
    Quote Originally Posted by FireHead
    Code:
    *final = &byte;  /* Make this 'char' hold an address. Wrong! */
    I disagree with above comment.
    According GCC 4.0.28 I get a warning only the above mentioned code line.

    But if I change it to
    Code:
    *final = (int) &byte ;
    The warning disappears.
    I don't care if you disagree with it or not. A char is not a char *. If it was the same thing, how would you get the contents of a pointer from an address? You aren't even attempting to make sense. You're just mad because someone told you your code was crap.

    You know what, I don't care. I don't care about you and your crappy code. Fix your own problems from now on.


    Quzah.
    Hope is the first step on the road to disappointment.

  11. #26
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    If you had actually done that, it would have barfed all over those // comments.

    How about starting again with a simple program which just demonstrates ONE of the problems you have.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. When and when not to use malloc()?
    By John.H in forum C Programming
    Replies: 5
    Last Post: 03-24-2003, 06:00 PM