C question

you have memory leek
Code:
int main(){
    char *c = stringcat("coffee","cup",3);
    printf("%s", c);

    free(c);
    return 0;
}

should fix this
 
Better version is
Code:
char *f = (char *)malloc(str1_length + n);        
strncpy(f, str1, str1_length);
strncpy(&f[str1_length], str2, n);
1st strncpy prevents your `f` from overflowing. afaik using strncpy is always more secure than strcpy.. Plus, this code easier and should be faster
 
For concatenation of several strings/integers/what-ever I use libc's asprintf():

PHP:
char *ptr = NULL, s1[] = "cows", s2[] = "milk";
int liters = 5;

asprintf(&ptr, "%s gave %d liters of %s.", s1, liters, s2);
assert(ptr != NULL);

printf("STRING: '%s'\n", ptr);
free(ptr);
 
killasmurf86 said:
you have memory leek
Code:
int main(){
    char *c = stringcat("coffee","cup",3);
    printf("%s", c);

    free(c);
    return 0;
}

should fix this
Doesn't FreeBSD free allocated memory at the completion of program? Smth like exit(3) does to open streams.
 
fairy said:
Doesn't FreeBSD free allocated memory at the completion of program? Smth like exit(3) does to open streams.

But, what if your program runs for years without exiting, and keeps concatenating strings? [you get my point]
 
killasmurf86 said:
But, what if your program runs for years without exiting, and keeps concatenating strings? [you get my point]
I belive such programs cant run for years :e
 
killasmurf86 said:
But, what if your program runs for years without exiting, and keeps concatenating strings? [you get my point]
Then it will never reach free() statement either. Stretching my point ad absurdum isn't substitute for an answer.
 
Hmm, to make a small concatinating program run for years, I would put it in a loop.

To make sure it does not memory leak for all those years, I would put the free() in the loop also.

Wouldn't do much useful, but at least it wouldn't leak :)
 
Its not about just how practical are the deallocations, its about coding style (correctness of it). It does not matter if your code will just be ran once in entire program's life, it is good coding practice to always deallocate memory after you are done using it. After you get used to deallocate your mallocs/news every time, there will be small chance of big memory leaks appearing in your more vital code segments when you forget to do so.
 
Agree with expl. Clean and correct code is important step on road to serious projects.
Its not essential which size program, correct memory handling must be a standard for any programmer.
 
line 5 is declaration of the function. It might be confusing because Business_Woman's separation of codeblocks is terrible.
 
psycho said:
i'm just curious about this code.
Line 5.
char *stringcat
Is that function? Why declaring this pointer?

It declares the return of that function. In this case the function returns a pointer to a character array.
 
Back
Top