Search code examples
cmallocstrcpycalloc

is malloc + strcpy function as good as calloc?


I've been looking for an answer to my question but I couldn't find any.

I've read several times the difference of malloc and calloc. If you have an issue with speed, you should use malloc since calloc allocates + initializes the buffer to 0.

Now, in my case, I should stick to malloc because its faster, but I still want to make sure that Id still get the correct data.

Does a call to strcpy after malloc is as good as calling calloc? I know that calloc isnt capable of copying a value of string one to the other. But I want to know if it is as safe as calloc since you used strcpy?


[update from comment:]

I declare and allocate the requersted memory..

char * commands = malloc(1000); 

Then compose the awk commands that I need and save it in commands.

strcpy(commands,"awk '{ print $0}' running-config.txt" ); 

That's how I used it.


Solution

  • Does a call to strcpy after malloc is as good as calling calloc?

    No, as strcpy(buffer, "") only sets the memory's 1st byte to 0, whereas calloc() zeros out the entire memory allocated.

    strcpy(buffer, ""); is equivalent to buffer[0] = '\0';. I tend to say the latter is faster.

    Whether strcpy()'s behaviour is enough of initialisation depends on the context/use-case.


    Update:

    As per your updated question, there does not seem to be any need to initialise the memory on allocation. (e.g. by using calloc(), as the call to strcpy() does it. But be aware that strcpy() leaves uninitialsed all unused memory (out of the allcoated memory). That is only strlen("awk '{ print $0}' running-config.txt") + 1 bytes out of the 1000 bytes allocated get initialised.