C语言 如何清除C中的内存内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13454036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to clear memory contents in C?
提问by gizgok
I'm defining a char pointer in this manner.
我正在以这种方式定义一个字符指针。
char *s=(char *)malloc(10);
After I fill in all possible values that can fit here, I want to clear whatever I wrote to s and without using malloc again want to write in s? How can I do this?
在我填写了适合这里的所有可能值后,我想清除我写给 s 的任何内容,并且不再使用 malloc 想要在 s 中写入?我怎样才能做到这一点?
I need to update the contents but if in the last iteration not all values are updated, then I'll be processing over old values which I do not want to do.
我需要更新内容,但是如果在最后一次迭代中没有更新所有值,那么我将处理我不想做的旧值。
回答by Olaf Dietsche
Be careful!
当心!
malloc(sizeof(2*5))is the same as malloc(sizeof(int))and allocates just 4 bytes on a 32 bit system. If you want to allocate 10 bytes use malloc(2 * 5).
malloc(sizeof(2*5))malloc(sizeof(int))与在 32 位系统上仅分配 4 个字节相同。如果要分配 10 个字节,请使用malloc(2 * 5).
You can clear the memory allocated by malloc()with memset(s, 0, 10)or memset(s, 0, sizeof(int)), just in case this was really what you intended.
您可以malloc()使用memset(s, 0, 10)或清除分配的内存memset(s, 0, sizeof(int)),以防万一这确实是您想要的。
See man memset.
参见man memset。
Another way to clear the memory is using callocinstead of malloc. This allocates the memory as malloc does, but sets the memory to zero as well.
清除内存的另一种方法是使用calloc而不是 malloc。这会像 malloc 一样分配内存,但也会将内存设置为零。
回答by unwind
A couple of observations:
几个观察:
- You don't need to cast the return value of
malloc()in C. - Your
malloc()argument looks wrong; note thatsizeofis an operator, not a function. It will evaluate to the size of the type of its argument: 2 * 5 has typeint, so the value will probably be 4. Note that this is the same for all integer expressions:sizeof 1is the same assizeof 100000000.
- 您不需要转换
malloc()C 中的返回值。 - 你的
malloc()论点看起来不对;请注意,这sizeof是一个运算符,而不是一个函数。它将计算其参数类型的大小: 2 * 5 具有 typeint,因此该值可能是 4。请注意,这对于所有整数表达式sizeof 1都是相同的:与 相同sizeof 100000000。
Your question is very unclear, it's not easy to understand why you feel you have to "clear" the string area. Memory is memory, it will hold what you last wrote to it, there's no need to "clear" it between writes. In fact, a "clear" is just a write of some specific value.
你的问题很不清楚,不容易理解为什么你觉得你必须“清除”字符串区域。内存就是内存,它将保存您上次写入的内容,无需在两次写入之间“清除”它。事实上,“清除”只是一些特定值的写入。
回答by Jason
You can "clear" memory by using memset, and setting all the bytes in the memory block to 0. So for instance:
您可以通过使用“清除”内存memset,并将内存块中的所有字节设置为0。所以例如:
#define MEMORY_BLOCK 10
//allocate memory
unsigned char* s = malloc(MEMORY_BLOCK);
//... do stuff
//clear memory
memset(s, 0, MEMORY_BLOCK);

