The Way to Programming
The Way to Programming
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?
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).
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.
Sign in to your account