• C Programming memory allocation

    Fierro Member

    I’m currently trying to write some code but I need some help with making things a little bit more efficient.

    First of all I have a standard char * with a lot of memory destined towards it and I need to append to its end just a few more bytes (at most 72 bytes to the end) but I don’t want to allocate a new char * with (size+72) length… Is there a way for doing this with considerable speed?

    The other issue is that I need to allocate a lot of space and so I call malloc a lot. But after I do it I need to be sure that all the allocated bytes are set to 0. I’m using memset for this but it seems like it’s a rather time costly procedure… Is there a way to avoid memset by defining malloc to automatically zero out memory? Or a function that is faster than memset?

  • SapnaVishwas Member

    Use realloc. Example:

    http://www.tutorialspoint.com/c_standard_library/c_function_realloc.htm

    #include 
    #include 
    
    int main()
    {
       char *str;
    
       /* Initial memory allocation */
       str = (char *) malloc(15);
       strcpy(str, "tutorialspoint");
       printf("String = %s,  Address = %u\n", str, str);
    
       /* Reallocating memory */
       str = (char *) realloc(str, 25);
       strcat(str, ".com");
       printf("String = %s,  Address = %u\n", str, str);
    
       free(str);
       
       return(0);
    }
    

    When you run it, it returns:

    String = tutorialspoint, Address = 355090448
    String = tutorialspoint.com, Address = 355090448
    

    2) Instead of malloc and memset you can use calloc. It sets all the allocated values to zero, aka clear-alloc (calloc).

  • Amit Member

    Yes and no. If there is enough memory space at the end of the allocated space it can just extend the allocation. See for instance the example I linked you above – after the “reallocation” the start of the array (aka the pointer) points again to the same memory address. If however there is not enough memory at the end, it will have to allocate a new memory, copy the old values to the new place and free the old memory.

  • Abhey Member

    Strcpy and strcat are not safe they are prone to bugs and buffer overflow exploitation. Use memcpy it’s quicker because the function does not check each copied byte for a null byte and is much safer

Viewing 3 reply threads
  • You must be logged in to reply to this topic.
en_USEnglish