Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory in C Function

Its memory wastage vs cpu utilization question.

If I want to merge 3 strings:

  • Approach 1: Should I take all string lengths (strlen) and then allocate.

    char *s = malloc(strlen(s1)+strlen(s2)+strlen(s3)+1);
    

OR

  • Approach 2: I should assume 1025 and allocate considering the fact that I know the strings will never go beyond 1025.

    #define MAX 1025
    char *s = malloc(MAX);
    

Please suggest.

like image 792
Nathan Avatar asked Mar 14 '26 16:03

Nathan


2 Answers

Allocate memory for all 3 strings is better.

But if you are 100% (bolded because it is very important) sure that the string never exceed the fixed length, then go ahead. You have to foresee whether you may add things in the future that may exceed the max length, and you have to consider whether user input in any way can overflow the limit.

In case you may not need everything, you can also allocate fixed buffer and truncate the rest of the string if it is too long.

If the string has potential to grow very long (a hundreds of MB), then you shouldn't use this approach. In this case, the solution depends on your application.

like image 116
nhahtdh Avatar answered Mar 17 '26 08:03

nhahtdh


Your malloc line looks fine.

The problem with your other alternative, assuming a fixed length, is that you may change your mind later about the fixed length without changing all of the corresponding problems in your code.

like image 37
sblom Avatar answered Mar 17 '26 09:03

sblom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!