Malloc的字符串包含垃圾值 [英] Malloc'ed string contains garbage values

查看:84
本文介绍了Malloc的字符串包含垃圾值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将Objective-C库转换为C库,以期使其跨平台.但是,直到我将其发送出去进行处理,一切似乎都还可以.

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.

紧跟在这样的malloc字符串之后:

Right after a malloc'd string like so:

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

我会看到theString为\ x03,* theString为"3'\ 003'".

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

起初我以为这只是奇怪的内存,因为我还没有输入strcat或其他内容,但是那个奇怪的起始字符会继续存在,并在我执行类似的malloc的其他所有位置重复出现.

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.

如果我想安全地将其转换为NSString,有人可以向我解释这是什么以及如何处理吗?

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

推荐答案

不能保证将malloc返回的值设置为任何特定值.仅保证指向您拥有的长度至少与指定长度一样长的内存.如果您希望将内存初始化为某个值,则需要您自己进行.或者使用calloc将内存清零.

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.

这篇关于Malloc的字符串包含垃圾值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆