【发布时间】:2016-04-08 01:38:12
【问题描述】:
今天我正在尝试编写一些代码,但我发现自己有时需要为指针分配一块内存。程序没问题,用valgrind检查也没问题。
在我开始查看整个代码后,我意识到我所做的是,内存是为 int a 分配的,而不是指针。
我是一个学习C只是为了好玩的人,我阅读了一些书籍和数百个教程,但我从未见过任何关于此类的提及,所以我真的需要在这里进行解释。
我试着做了一个小程序来解释上下文:
#include<stdio.h>
#include<stdlib.h>
void createMe(int *a);
void freeMe(int *b);
int main(void){
int a;
createMe(&a);
}
void createMe(int *ptr){
ptr = malloc(256);
*ptr = 10;
printf("A = %d\n",*ptr);
freeMe(ptr);
}
void freeMe(int *ptr){
free(ptr);
}
这里我有int a,我在createMe(&a);中传递了它的地址
create 函数将指针作为参数,因此我必须使用&a。
现在对我来说奇怪的部分来了:
在createMe(); 内,我在该指针ptr 上调用malloc,这是函数的参数。
在作为create() 函数的参数的指针中添加/使用的内存块到底在哪里,或者它在main 中发送到a?
就我到现在为止的阅读/学习而言:
1) a 没有获得该内存块,因为 a 是 int 而不是 int*。
2) 函数参数ptr 是否得到那个内存块?如果是,我怎么从来没有读过这样的东西。
我将Linux mint 17.3 与GCC-4.8.5 和GCC-5.2.0 一起使用
这是Valgrind的结果:
==6793== Memcheck, a memory error detector
==6793== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==6793== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==6793== Command: ./program
==6793==
A = 10
==6793==
==6793== HEAP SUMMARY:
==6793== in use at exit: 0 bytes in 0 blocks
==6793== total heap usage: 1 allocs, 1 frees, 256 bytes allocated
==6793==
==6793== All heap blocks were freed -- no leaks are possible
==6793==
==6793== For counts of detected and suppressed errors, rerun with: -v
==6793== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
如您所见,内存分配发生了,free 也发生了。
GCC Flags 是:
-Wall -Wextra -Werror -Wstrict-prototypes -Wconversion -Wmissing-prototypes -Wold-style-definition -std=c11 -O0 -g
【问题讨论】:
-
提示:这里根本不需要
a。尝试传递NULL。它也能正常工作。 -
@cad 感谢您的回复。我在问是否可以为函数参数创建一块内存。我从来没有读过那样的东西。 :)
标签: c pointers malloc parameter-passing