Returning a pointer from a function - c

This is in reference to this question: Why is a pointer to pointer needed to allocate memory in this function?
The answer to the question explained why this didn't work:
void three(int * p)
{
p = (int *) malloc(sizeof(int));
*p = 3;
}
void main()
{
int *p = 0;
three(p);
printf("%d", *p);
}
... but this works:
void three(int ** p)
{
*p = (int *) malloc(sizeof(int));
**p = 3;
}
void main()
{
int *p = 0;
three(&p);
printf("%d", *p);
}
This also works, by returning a pointer from the function. Why is that?
int* three(int * p)
{
p = (int *) malloc(sizeof(int));
*p = 3;
return p;
}
void main()
{
int *p = 0;
p = three(p);
printf("%d", *p);
}

int* three(int * p)
{
p = (int *) malloc(sizeof(int));
*p=3;
return p;
}
Because here you're returning a copy of the pointer p and this pointer now points to valid memory, which contains the value 3.
You originally passed in a copy of your p as an argument, so you're not changing the one you passed in, but a copy. Then you return that copy, and assign it.
From the comment, which is a very valid point, this will also work just as well:
int* three()
{
//no need to pass anything in. Just return it.
int * p = (int *) malloc(sizeof(int));
*p=3;
return p;
}

They're completely different (and if you truly understand why the first works, you'd see there's no connection).
By returning, you're not attempting to modify the already existing pointer from inside the function. You're just returning a new pointer, and assigning its value outside.

Look at it as a question of scope.
In main() you have a pointer p.
int *p = 0;
p in main is set to NULL. When you make a call to the three function passing it p:
three(p);
You are passing a pointer to NULL. What happens to it is outside the scope of main(). main() does not know, nor does it care what happens. main() only cares about its copy of p, which at this point is still set to NULL.
Unless I reassign p within the scope of main() (including handing off the address of p), p is still just a pointer pointing to NULL.
If I give you this code:
void main()
{
int *p = 0;
funcX(p);
printf("%d",*p);
}
You can tell me definitively what is going to happen (Segmentation fault) without ever knowing what funcX() does because we're passing a copy of the pointer to this function, but a copy doesn't affect the original.
But if I give you this code:
void main()
{
int *p = 0;
funcX(&p);
printf("%d",*p);
}
You can't tell me what will happen unless you know what funcX() is doing.
That make sense?

Related

shows variable uninitialized when calling a function that uses malloc [duplicate]

This question already has answers here:
Changing address contained by pointer using function
(5 answers)
Closed last year.
# include<stdio.h>
# include<stdlib.h>
void fun(int *a)
{
a = (int*)malloc(sizeof(int));
}
int main(void)
{
int *p;
fun(p);
*p = 6;
printf("%d\n",*p);
free(p);
return(0);
}
In vs code this shows error because int *p is uninitialized and tells me to initialize the variable 'p' to NULL to silence this warning. But when I did that it compiled but showed segmentation fault, likely because I'm assigning 6 to the null address, so how do I fix this?
This function
void fun(int *a)
{
a = (int*)malloc(sizeof(int));
}
changes its own local variable (parameter) a. That is the function deals with a copy of the value of the passed pointer p
int *p;
fun(p);
The pointer p stays unchanged and uninitialized.
To make the program correct you need to change the code the following way
void fun(int **a)
{
*a = (int*)malloc(sizeof(int));
}
//...
int *p;
fun( &p);
Though in this case it would be better to declare and define the function like
int * fun( void )
{
return malloc(sizeof(int));
}
//...
int *p = fun();
if ( p )
{
*p = 6;
printf("%d\n",*p);
}
free(p);

Why is the pointer's value still 20?

void func(char *p)
{
int q = 13;
p = &q;
printf("%d\n", *p);
}
void main(void)
{
int var = 20;
int *p = &var;
printf("%d\n", *p);
func(p);
printf("%d\n", *p);
}
How come at the function exit the pointer is still 20?
I was hopping when the func() ends, the pointer is modified in it, in the last printf(), the *p value would be pointing some random stuff from the stack.
What you had is this
void func(char *p)
{
int q = 13;
p = &q;
}
This means "make p point to q" and changes value of p, which is just a variable inside the function. No variable value changes are reflected outside the function.
If you were to write this
void func(char *p)
{
int q = 13;
*p = q;
}
This would mean "make the variable to which p points to change its value to 13" and that would be seen outside, meaning the variable var in main would change its value (depends on endianness what it would be since it's int and not char as the pointer claims it to be).
If you want to change the pointer's value in main you need a double pointer:
void func(char **p)
{
int q = 13;
*p = &q;
printf("%d\n", *p);
}
This would mean "make the pointer to which p points to point to a local variable q" and in this case you would have a dangling pointer as you expected in main.
No, p itself is passed be value. Any change made to p inside func() will not be reflected back to main().
For sake of completeness, any changes made to the value pointed to by p (i.e., *p) would have been reflected back in main().

Segmentation Fault while malloc and sizeof

Sorry if I'm offending anyone but I started learning C this week and I got a segmentation fault while compiling this. Can I please have a second pair of eyes to help me with this error?
void Space(void *empty, size_p s)
{
empty = malloc(s);
}
int main()
{
int *p = NULL;
Space(p, sizeof(p));
*p = 7;
return;
}
empty is just a pointer variable - it contains "some" address, but it is still a local variable in the context of Space. If you want to update the value of int *p in Space, you'll need to pass a pointer to it:
int main()
{
int *p = NULL;
Space(&p, sizeof *p);
*p = 7;
return;
}
void Space(void **empty, size_p s)
{
*empty = malloc(s);
}
Also, you have a bug where you call Space: Space(p, sizeof(p));
sizeof(p) is the size of the int * variable but you want to allocate the size of an int as that's what you're storing in p. So that line should instead be:
Space(&p, sizeof *p);
void * Space(void *empty, size_t s)
{
empty = malloc(s);
return empty;
}
int main()
{
int *p = NULL;
p = Space(p, sizeof(int));
*p = 7;
return 0;
}
You can change the Space function to return a void * or an int *. The variable empty is a copy of the pointer in main. When you change the value in Space, because it is a copy, the change never makes it back to main.
I changed sizeof(p) to sizeof(int). This is more of personal preference but I try to only give types as the argument to sizeof. You can get surprising results when you apply sizeof to variables.
I really like #DIMMSum's answer but I know pointer-to-a-pointer can be confusing especially when starting out.

how to pass the pointer to a function and assign the value to the variable pointed to in C?

I know the c always pass by values, but if I have a pointer:
int i = 4;
int * p;
p = &i;
then I have a function, how to pass pointer p to it and change the value of variable i?
void changeValue(int *p)
{
}
how to pass the pointer and change the variable pointed by p?
This simple example shows how to pass a pointer (i.e. not a value) and recieve back through that pointer, the new value held by the integer. Note the reduced number of variables. i.e. there is no need necessarily to create a separate copy of int *p;. Nor is it necessary in this case to initialize p: p = &i; to the address of i.
int changeValue(int *);
int main(void)
{
int i=15;
changeValue(&i);
return 0;
}
int changeValue(int *p) //prototyped to accept int *
{
return *p = 3;
}
If you do want to create a pointer in the first place, and pass that pointer, then:
int changeValue(int *);
int main(void)
{
int i=15;
int *p;
p = &i;
*p; // *p == 15 at this point
//since p is already a pointer, just pass
//it as is
changeValue(p);
return 0;
}
int changeValue(int *q) //prototyped to accept int *
{
return *q = 3;
}
It is important to note that your statement: I know the c always pass by values is not correct. It is more common for functions to be written such that pointers are passed because often a pointer is smaller, and more efficient to pass around than the actual variable, especially when large arrays, or structs are used. Keep in mind though that passing &i (the address of i) works just as well as passing p if passing a pointer is called for.
Simply pass it by calling changeValue as
changeValue(p);
and change the value of variable pointed by it (i) by assigning a value to the *p in changeValue()
void changeValue(int *p)
{
*p = an int value;
}
void changeValue( int* ) ;
int main( void )
{
int i = 4; // Suppose i is stored at address 1000h
int * p;
p = &i; // Now p stores the address of i that is 1000h
changeValue(p); // Can also be written as changeValue(&i);
// Here you are passing the address of i to changeValue function
return 0 ;
}
void changeValue( int* p ) // Accept a parameter of type int*
{
*p = 100 ; // store the value 100 at address 1000h
return ;
}
int i = 4;
int * p = &i;
changeValue(p);
printf("%d",*p);
void changeValue(int *p)
{
*p = 5;
}
Full program - http://ideone.com/DCvhxE
If you dereference the pointer in changeValue and assign to it, it will alter the value of i in the calling frame.
e.g.:
void changeValue(int *p)
{
*p = 0;
}

Why I've allocated a pointer memory in a function, but it's also NULL?

The code confused me.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void create_int(int *p)
{
p = (int *) malloc(sizeof(int));
}
int main()
{
int *p = NULL;
create_int(p);
assert(p != NULL); /* failed. why? I've allocated memory for it. */
return 0;
}
You are not passing the pointer value back from the function. Try:
void create_int(int **p) {
*p = (int *) malloc(sizeof(int));
}
int main() {
int *p = NULL;
create_int(&p);
assert(p != NULL); /* failed. why? I've allocated memory for it. */
return 0;
}
The variable p in the function create_int is a copy of the variable p in main. So any changes made to p in the called function does not get reflected in main.
To make the change get reflected in main you need to either:
Return the changed value:
int* create_int(int *p) {
p = malloc(sizeof(int));
// err checking
return p:
}
...
// in main:
p = create_int(p);
Or pass the address of p as:
void create_int(int **p) {
*p = malloc(sizeof(int));
// err checking
}
...
// in main:
create_int(&p);
You need a pointer to a pointer like this:
void create_int(int **p)
{
*p = (int *) malloc(sizeof(int));
}
int main()
{
int *p = NULL;
create_int(&p);
assert(p != NULL); /* failed. why? I've allocated memory for it. */
return 0;
}
As folks have pointed out, it's failing since you're not actually changing the pointer that the caller has.
A different way to think about the code might be to notice that it's basically wrapping malloc(), i.e. it's doing a memory allocation but with intelligence added. In that case, why not make it have the same prototype (=call signature) as malloc()? That makes it clearer in the caller's context what's going on, and easier to use:
int * create_int(void)
{
return malloc(sizeof (int));
}
int main(void)
{
int *p = create_int();
assert(p != NULL);
return 0;
}
Also, in C you should never cast the return value of malloc() (see Do I cast the result of malloc?).
You need to send a pointer to a pointer to be able to assign a memory to it via a function
void create_int(int **p)
{
*p = (int*)malloc(sizeof_int));
}
int main()
{
int* p = NULL;
create_int(&p);
assert(p != NULL);
return 0;
}
Your code contains two pointers: one in the create_int function and another one in main. When you call create_int, a copy of the pointer in main is made and used, then eliminated when the create_int function returns.
So, any changes you did to the copy within create_int remain there and are not propagated back to main.
The only way to propagate changes between functions in C (aside from, obviously, returning new values) is to pass a pointer to the changed values. This way, while the pointer being passed will be copied, the value that it points to will be the same, so changes will apply.
Since you're trying to change a pointer, you need a pointer-to-pointer.
void create_int(int **pp)
{
// this changes the pointer that `p` points to.
*pp = (int *) malloc(sizeof(int));
}
int main()
{
int *p = NULL;
// this sends a pointer to the pointer p in main
create_int(&p);
assert(p != NULL);
return 0;
}

Resources