tags:

views:

137

answers:

1

I just converted an Objective-C library to a C library in the hopes of making it cross platform. However, everything appears to do okay until I send this thing off to be processed.

It's at the point I get an error.

Looking back a few revisions, I noticed something in the debugger.

Right after a malloc'd string like so:

char *theString = malloc(SOME_SIZE * sizeof(char));

I would see that theString is \x03 and *theString is "3 '\003'".

I assumed at first that this was just weird memory since I haven't don a strcat or anything to it, but that odd starting character(s) carry through, and recurs at every other point that I perform a similar malloc.

In terms of normal processing, this is fine. Unfortunately, I don't understand what it is, otherwise, I'd just do something drastic like cutting off that first character or something.

Can someone explain to me what that is and how I deal with it if I want to convert it to an NSString safely?

+9  A: 

The value returned by malloc is not guaranteed to be set to any specific value. It's only guaranteed to point to memory you own of length at least as long as you specified. If you want the memory initalized to some value you'll need to do it yourself. Or alternately use calloc which will zero out the memory.

JaredPar
Note that calloc should not be used unless necessary (e.g. for structs or arrays).
Matthew Flaschen
Can you elaborate on this? I take you to mean that a pointer to a single element shouldn't use calloc (as in, for built-in types)?
Sam
The zeroing is potentially expensive. Also, I've seen weird things happen when using calloc() before, which were all solved by switching to use malloc() followed by bzero().
Jim Dovey