Ako deklarises neki pointer koji ce ti koristiti za kopiranje jednog pointera, onda ne sluzi ni cemu da alociras memoriju.
Primer:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *good_to_up(char *str)
{
char *tmp;
/* Pravim kopiju str-a da ne bih izgubio adresu gde se string nalazi
** Nema potrebe da se malloc-uje zato sto pravimo samo kopiju str-a, tj
** kopiju adrese gde se nalazi string
*/
tmp = str;
while(*str != '\0')
{
if((*str >= 97) && (*str <= 122))
*str = *str - 32;
str++;
}
/* Vracam staru adresu str-a, tamo gde pocinje string */
return(tmp);
}
char *bad_to_up(char *str)
{
while(*str != '\0')
{
if((*str >= 97) && (*str <= 122))
*str = *str - 32;
str++;
}
/* Primetices da ovde vracamo adresu: str + strlen(str), zato sto smo presli preko celog
** stringa, a nismo sacuvali adresu gde se nalazi string
*/
return(str);
}
int main(int argc, char *argv[])
{
char *str;
str = malloc(10);
read(1, str, 10);
printf("||%s||\n", good_to_up(str));
printf("||%s||\n", bad_to_up(str));
return(0);
}
U mom primeru je cak greska alocirati memoriju za tmp. Ako alociras, ta memorija ce biti neupotrebljena, tj. onaj poznati memory-leak.
"The problem with the world is that everyone is a few drinks behind."
-Humphrey Bogart