Malloc'ed string contains garbage values

2020-05-05 17:55发布

问题:

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?

回答1:

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.