我想了解更多关于内存分配的知识,所以我在下面写了一些测试代码,看看如果我尝试分配比我需要的内存更小的内存会发生什么。如果我使用大小错误的malloc会发生什么?
#include <stdlib.h>
#include <stdio.h>
typedef struct {
char *message;
int number;
} Object;
int main(int argc, char *argv[]) {
Object *obj = malloc(sizeof(Object) - 8);
printf("The size of the struct is: %ld\n", sizeof(Object));
printf("The size of what was allocated is: %ld\n", sizeof(*obj));
obj->message = "Hello there! My name is Chris!";
obj->number = 435543;
puts(obj->message);
printf("%d\n", obj->number);
free(obj);
return 0;
}
首先,是sizeof(* obj)正确的方法来看看在这种情况下实际分配了多少内存?其次,即使我没有分配足够的空间,为什么仍然可以为结构对象赋值?
我的操作系统是Ubuntu的12.10 64位,编译器是gcc 4.7.2
这里是Valgrind的输出:
==14257== Memcheck, a memory error detector
==14257== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==14257== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==14257== Command: ./ex
==14257==
The size of the struct is: 16
The size of what was allocated is: 16
==14257== Invalid write of size 4
==14257== at 0x400640: main (ex.c:15)
==14257== Address 0x51f1048 is 0 bytes after a block of size 8 alloc'd
==14257== at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14257== by 0x400604: main (ex.c:10)
==14257==
Hello there! My name is Chris!
==14257== Invalid read of size 4
==14257== at 0x40065A: main (ex.c:18)
==14257== Address 0x51f1048 is 0 bytes after a block of size 8 alloc'd
==14257== at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14257== by 0x400604: main (ex.c:10)
==14257==
435543
==14257==
==14257== HEAP SUMMARY:
==14257== in use at exit: 0 bytes in 0 blocks
==14257== total heap usage: 1 allocs, 1 frees, 8 bytes allocated
==14257==
==14257== All heap blocks were freed -- no leaks are possible
==14257==
==14257== For counts of detected and suppressed errors, rerun with: -v
==14257== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 2 from 2)
尝试使用valgrind查看所有内存分配。 – squiguy
你正在进入未定义行为的领域。未定义的行为包括程序工作正常。 – user93353