2012-10-04

Whenever I wonder if I'm a decent C/C++ programmer, I just need to look around some programming websites.

This is one which really had me wondering if this was a new trick I should have known - then I realised - no, it wasn't...

http://www.dsxchange.com/viewtopic.php?t=126804&postdays=0&postorder=asc&start=15

As an example.

To allocate a block of memory to store a copy of a string in, we should all use:

char *ptr = new char[strlen(sourcestring) * sizeof(char *)];

This is OK 'because sizeof(char *) is always 1'. Also, you should use 'new' rather than 'malloc' because 'new' will manage the memory allocation & freeing for you, so you won't get memory leaks.

I certainly wish I'd known that trick.

I've been living with the misconception for years that:

sizeof(char *) is probably either 4 or 8, but pretty certainly not '1' (except on computers with 256 or fewer bytes of memory)

strlen(string) is the length of the string. For storing a string in a C character array, you need 1 extra byte (in this case, probably not an problem, except for empty strings, because of the massive overallocation caused by the previous issue)

I always thought a 'new' should have a matching 'delete'. I could have saved so much typing and thinking if I'd known that 'new' managed the memory for you.

So, I feel humbled by the superior knowledge of the people on these forums.

(It's just slightly worrying that this is from a forum for people using IBM's DataStage, which is a thing for high performance handling of large databases. So, these people could well be working for your bank, or health service or government)

Show more