Thread: Best method to alloc memory for string and desalloc.

  1. #1
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184

    Best method to alloc memory for string and desalloc.

    how the Best method to alloc memory for string and after desalloc.

    Im using this:

    Code:
    void ClearStr ( char * pString )
    {
       *pString = '\0';
    }
    
    char *substr(const char *pstr, int start, int numchars) 
    {
    	char *pnew = malloc(numchars+1);
    	
    	strncpy(pnew, pstr + start, numchars);
    	pnew[numchars] = '\0';
    	return pnew;
    }
    
    char *teste; 
    char *teste2;
    
    teste = ReceiveComm();
    teste2 = substr (teste, 1, 6);
    
    ClearStr (teste);
    this is executed all 5 minutes, for all long program be executed.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by sergioms
    this is executed all 5 minutes, for all long program be executed.
    I suspect that most of the time was spent in ReceiveComm(). Are you sure that you have correctly identified the bottle necks in your code? Note that ClearStr() only sets the string to an empty string but does not actually deallocate the memory, but presumably that was intentional.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    yes, this was intentional.

    Code:
    char* funcTest(){
           char *rxteste;
    
           rxteste = substr (teste, 1, 6);
           return rxteste ;
    }
    A Question, if a call a function funcTest, the variable rxteste is alloced and desalloced when the function end ?

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    It depends on what you mean by "desalloced" -- you still own the memory, since you malloc'ed it and never freed it. The only thing gone is the name rxteste.

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by sergioms View Post
    yes, this was intentional.

    Code:
    char* funcTest(){
           char *rxteste;
    
           rxteste = substr (teste, 1, 6);
           return rxteste ;
    }
    A Question, if a call a function funcTest, the variable rxteste is alloced and desalloced when the function end ?
    rxteste is allocated in substr, but not de-allocated - and you can't deallocate it here either, since you are returning it to the calling function - and if you deallocate it there, it would not be valid later on (in the calling function).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    and, when I would to use malloc ?

    in "Global Variables?"

    and when I need a string with value all time changed.?

  7. #7
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    Quote Originally Posted by matsp View Post
    rxteste is allocated in substr, but not de-allocated - and you can't deallocate it here either, since you are returning it to the calling function - and if you deallocate it there, it would not be valid later on (in the calling function).

    --
    Mats

    ok, in this case
    when i alloc in substr, where and how to de-alloc this ?

    sorry for my english, and my inconvenience.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by sergioms
    when i alloc in substr, where and how to de-alloc this ?
    You would deallocate the memory when you no longer need to use it by using free(), which is also from <stdlib.h>.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by sergioms View Post
    ok, in this case
    when i alloc in substr, where and how to de-alloc this ?

    sorry for my english, and my inconvenience.
    From the back: Don't worry about your English - it's better than my italian or whatever you speak natively...

    You need to dealloc whereever the string is no longer needed. You haven't shown all the code [you don't need to show us all code - just that I can't tell you what the right place is when I can't see it - but I can describe it], so I don't know what it is that you do with the string.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    ok,

    I have a string receiving text at 200 milleseconds. (strReceiveCom)

    This String is processed as a packet

    Example: [2]FUNC[9]VALUE1[9]VALUE 2[9][13][10]

    *where: [] indicates a decimal value in ASCII.

    This packet, is splited in others strings:

    strPckFunction = substr (strReceiveCom, 1,4);
    strValue1 = substr (strReceiveCom, 6, iTabPos);

    the strings strPckFunction and strValue1 is processed locally and after the strReceiveCom value need cleaned to receive more text.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    So, do you have enough time to process the value in 200ms every time, or do you need to build up a queue of elements and then process then later?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    No, I dont need to build up a queue, I Can clean actual strReceiveCom and process the last packet, I can lose all old text.

  13. #13
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    So basically, when you are finished with strValue1 and strPckFunction, you should free both of those strings.

    Although I would probably prefer to not allocate memory at all, instead use a local char array to store the value and function strings in, and pass that to the substr() function as an argument. That reduces the overhead of calling malloc and free, as well as reducing the chance of "forgetting" to free the string.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  14. #14
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    Code:
    char *substr(char **Pnew, const char *pstr, int start, int numchars) 
    {
    	strncpy(pnew, pstr + start, numchars);
    	pnew[numchars] = '\0';
    	return pnew;
    }
    
    void Test (){
    	char *pnew = malloc(numchars+1);
    
                    substr(&pnew, "TESTE", 0,2) ;
    
    }
    is this ?

  15. #15
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I'm wondering if part of your problem has to do with "returns address of local variable"...anyway, if you know that your string is not going to exceed a certain size, rather than returning a malloc'd pointer, you can pass the string in as an argument instead. Even with with malloc, this may be easier since then string will be allocated and free'd in the same place:
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    void substring (char *string, char *substr, int numchars) {
    	strncpy(substr,string,numchars);
            substr[numchars+1]='\0';
    }	
    
    int main() {
    	char string[]="ciao mondo sergio", sub[6], 
    		*sub2=malloc(7);
    	substring(&string[11],sub,6);		// without malloc
    	printf("%s\n",sub);
    	substring(&string[5],sub2,5);		// with malloc...
    	printf("%s\n",sub2);
    	free(sub2);				// ...free when finished
    	return 0;
    }
    Output:
    Code:
    sergio
    mondo
    Notice the string is passed in starting with the address of the first character of the substring, rather than using int start (a possibility).

    Of course in my example, function substring() ends up being an anagram of strncpy, but hopefully there's something here you can use.
    Last edited by MK27; 01-05-2009 at 02:17 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed