Today I was trying to code something and i found my self at some point that i need to allocate a block of memory needed for a pointer. The program was OK and checked with valgrind was also OK.
Some how after I started to review the whole code i realized that what i did, was that the memory was allocated for int a which is not a pointer.
I'm a person which learn C just for fun, I read some books and hundreds of Tutorials, but i never saw any mention about something like this so I really need an Explanation here.
I tried to make a small program to explain the context:
#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);
}
Here i have int a and i passed its address in createMe(&a);
The create function takes a pointer as argument so i had to use &a.
Now comes the strange part for me:
inside createMe(); i call malloc on that pointer ptr which is the argument of the function.
Where exactly it is that memory block added/used in the pointer which is the argument of create() function or it sent to a inside main?
As far as I read/learn until now:
1) a doesn't get that memory block because a is an int and not an int*.
2) does the function argument ptr get that memory block`?, if so, how comes that i never read something like that.
I used Linux mint 17.3 with GCC-4.8.5 and GCC-5.2.0
Here is the result of 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)
As you can see the memory allocation takes place and free takes place too.
And the GCC Flags are:
-Wall -Wextra -Werror -Wstrict-prototypes -Wconversion -Wmissing-prototypes -Wold-style-definition -std=c11 -O0 -g
ais not needed here at all. Try passingNULL. It'll work just as well.