简体   繁体   中英

Malloc'ed string contains garbage values

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM