上使用malloc分配内存的sizeof() [英] Using sizeof() on malloc'd memory
问题描述
可能重复:结果
有关的malloc和sizeof
我想读的字符串到一个程序。当我注意到弦有时被损坏,我尝试以下code:
I am trying to read strings into a program. When I noticed that the strings were sometimes being corrupted, I tried the following code:
void *mallocated = malloc(100);
printf("sizeof(mallocated) = %d\n", sizeof(mallocated));
据我的程序, mallocated
的大小为 8
,即使我分配的100个字节它。正因为如此,每当我尝试存储字符串长度超过8个字节,第8字节之后一切都会有时会消失。为什么会出现这种情况,而哪能prevent呢?
According to my program, the size of mallocated
was 8
, even though I allocated 100 bytes for it. Because of this, whenever I try to store a string longer than 8 bytes, everything after the 8th byte will sometimes disappear. Why is this happening, and how can I prevent it?
推荐答案
由于字符串指针的大小为8字节。下面是使用带有其相应的大小的sizeof()的一些例子。术语size_of()有时欺骗了不习惯使用它的人。你的情况,指针的大小为8字节。下面是一个典型的32位系统上重新presentation。
Because the size of the "string" pointer is 8 bytes. Here are some examples of using sizeof() with their appropriate "size". The term size_of() is sometimes deceiving for people not used to using it. In your case, the size of the pointer is 8 bytes.. below is a representation on a typical 32-bit system.
sizeof (char) = 1
sizeof (double) = 8
sizeof (float) = 4
sizeof (int) = 4
sizeof (long) = 4
sizeof (long long) = 8
sizeof (short) = 2
sizeof (void *) = 4
sizeof (clock_t) = 4
sizeof (pid_t) = 4
sizeof (size_t) = 4
sizeof (ssize_t) = 4
sizeof (time_t) = 4
您离开了你是如何确定你的字符串消失(字符数组)。它可能是被传递给函数,你需要通过明确的长度作为一个变量或跟踪它的地方。使用的sizeof()不会告诉你这一点。
You are leaving out how you are determining your string is disappearing (char array). It is probably being passed to a function, which you need to pass the explicit length as a variable or track it somewhere. Using sizeof() won't tell you this.
请参阅我的<一个href=\"http://stackoverflow.com/questions/2051462/question-about-why-string-is-truncated-on-first-instance-of-0\">$p$pvious这个问题,你会看到连我缺乏有了初步的了解。
See my previous question about this and you'll see even my lack of initial understanding.
这篇关于上使用malloc分配内存的sizeof()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!