[英]malloc returns pointer to allocated memory
自从我写C以来已经很长时间了。我的理解是malloc
返回一个指向新分配的内存区域的指针,该区域与以前的malloc
响应不重叠。 但是,我的程序(如下)似乎显示malloc
返回一个指向已分配区域中间的指针!
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int* bla;
int baz;
int qux;
int bar;
} foo;
int main() {
foo* foo = malloc(sizeof(foo));
int* arr = malloc(sizeof(int) * 10);
// my understanding of malloc is that `foo` and `bar` now point to
// non-overlapping allocated memory regions
printf("arr %p\n", arr); // but these print
printf("&(foo->bar) %p\n", &(foo->bar)); // the same address
foo->bar = 42;
printf("arr[0] = %d\n", arr[0]); // prints 42
return 0;
}
我正在使用以下命令进行编译和运行:
$ cc --version
Apple LLVM version 7.3.0 (clang-703.0.29)
Target: x86_64-apple-darwin15.3.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
$ cc main.c -o main
$ ./main
arr 0x7fa68bc03210
&(foo->bar) 0x7fa68bc03210
arr[0] = 42
我究竟做错了什么?
那是什么?!
foo* foo = malloc(sizeof(foo));
请使用不同的标识符!
foo* variable = malloc(sizeof(foo));
只是为了确保我测试了这个main()
:
int main() {
printf("sizeof(foo)=%zu\n", sizeof(foo));
foo* foo = malloc(sizeof(foo));
printf("sizeof(foo)=%zu\n", sizeof(foo));
}
输出(使用LLP64时为64位 ):
sizeof(foo)=24
sizeof(foo)=8
不要使用相同的标识符两次,您会感到意外。
typdef
别名与具有相同名称的实例声明之间没有冲突。 您可以但不建议执行您原来的操作,但是要从变量中获取大小,而不是尝试从类型中获取它。 特别:
foo *foo = malloc (sizeof *foo);
您可以在完整示例中进行确认:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *bla;
int baz;
int qux;
int bar;
} foo;
int main (void) {
foo *foo = malloc (sizeof *foo);
int *arr = malloc (sizeof *arr * 10);
printf ("arr %p\n", arr);
printf ("&(foo->bar) %p\n", &(foo->bar));
foo->bar = 42;
printf ("foo->bar = %d\n", foo->bar);
return 0;
}
示例输出
$ ./bin/foofoo
arr 0x17f3030
&(foo->bar) 0x17f3020
foo->bar = 42
使用以下代码
注意foo
实例的唯一名称
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int* bla;
int baz;
int qux;
int bar;
} foo;
int main()
{
foo* myfoo = malloc(sizeof(foo));
int* arr = malloc(sizeof(int) * 10);
// my understanding of malloc is that `foo` and `bar` now point to
// non-overlapping allocated memory regions
printf("arr %p\n", arr); // but these print
printf("&(foo->bar) %p\n", &(myfoo->bar)); // the same address
myfoo->bar = 42;
printf("arr[0] = %d\n", arr[0]); // prints 42
return 0;
}
输出为:
arr 0x1578030
&(foo->bar) 0x1578020
arr[0] = 0
这正是我所期望的。
我在gcc 4.8.4的ubuntu linux 14.04下编译了这个
使用:
gcc -ggdb -c -Wall -Wextra -pedantic -Wconversion -std=gnu99 myfile.c -o mybile.o
然后
gcc -ggdb -std=gnu99 myfile.o -o myfile
然后用
./myfile
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.