[SDL] ot - memory leaks
James Barrett
xucaen at gmail.com
Sat Aug 4 15:20:42 PDT 2007
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Christer Sandberg wrote:
> On Saturdayen den 4 August 2007, Lilith Calbridge wrote:
>> your pointers' states. Initialize all pointers to NULL when they're
>> declared.
> Talking about local variables I would general say in don't, since it will
> prevent the compiler from giving warnings for one of the common error
cases:
> void foo(int a, int b)
> {
> char *buf=NULL;
> if (a) {
> buf = malloc(100);
> if (buf==NULL) error();
> }
> if (b) {
> *buf = 0;
> }
> ...
> }
> This code crashes randomly depending on the values of a and b. Remove the
> initialization of buf in the declaration and you will get a warning
about the
> mistake, at least from a decent compiler.
>
Hi, just throwing in my 2 cents, and this is by no means the only way
to do this, but I would probably re-write that sample to be something
like:
void foo(int a, int b)
{
char *buf=NULL;
if (a) {
buf = malloc(100);
}
if (buf==NULL) {
error();
}
else if (b) {
*buf = 0;//we know buf has been allocated, so assign it a value;
}
...
}
Jim
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
iD8DBQFGtPu5QuDJiZ/QrH0RAoC/AKDU7/k9f5kNauVj0rTaViiEUpCK+gCgvzpd
KCIgIRUDx1/VhNJ43TOFSm0=
=bnpi
-----END PGP SIGNATURE-----
More information about the SDL
mailing list