-3

I have a function as follows:

void foo (int *check){
*check= 9;
printf("*check: %d\n",*check);
//when I print "*check" here, the value changes as 9.
}

This is the main function.

void main () {
int check=5;
foo(&check);
printf("check: %d\n",check);
//when I print "check", gives me 5. 
}

I want to change the value of "check" variable but it does not work. Where am I making mistake? Thank you!

I am using makefile while running it. Edit: malloc is deleted now it gives me Segmentation fault (core dumped) error

helloword
  • 5
  • 2
  • 3
    Why are you calling malloc inside foo? – Timbo Jul 27 '21 at 08:54
  • 3
    Skip `check= malloc(sizeof(int));` The memory is already allocated by the compiler for the variable you pass a pointer to. – Some programmer dude Jul 27 '21 at 08:54
  • 1
    `check= malloc(sizeof(int));` overwrites the value passed to the function, and creates a memory leak too. – Weather Vane Jul 27 '21 at 08:55
  • @Timbo when I delete that line, it gives me Segmentation fault (core dumped) error. – helloword Jul 27 '21 at 08:55
  • `foo` gets a copy of the pointer you pass to it. By allocating more memory, then assigning copy of the pointer to this new memory, you're not (as you've discovered) doing anything useful. Remove the first line of foo. – enhzflep Jul 27 '21 at 08:56
  • Also, add a malloc to the main, _then_ assign the value of 5. Example incoming shortly.. – enhzflep Jul 27 '21 at 08:57
  • 1
    "gives me Segmentation fault" can't reproduce, but you have not posted the [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example), the shortest *complete* code that shows what you have tried. – Weather Vane Jul 27 '21 at 08:59
  • 1
    The reason why this code does not work. You create a variable on the stack and assign it to five, then you pass the pointer to the variable in the function, in the function on the first line you change the pointer to a newly allocated memory in heap. The second line update the memory in the heap. At the end you have the pointer pointing to the heap memory with the value 9 and the variable on the stack which is still 5. If you want to change the variable on the stack please don't change the pointer within the function(malloc line). – Dima Jul 27 '21 at 09:00
  • Replace `check= malloc(sizeof(int));` with `int x; check = &x;` What do you think should happen now? – n. m. could be an AI Jul 27 '21 at 09:02
  • 1
    @enhzflep Why should `malloc` be used outside of `foo`? – Gerhardh Jul 27 '21 at 09:02
  • @Gerhardh - good question. It shouldn't. I'd erroneously thought of the problems caused by using const - i.e making the variable part of the non-writeable data segment. – enhzflep Jul 27 '21 at 09:07
  • _"when I print "check", gives me 5."_: well there is no code that prints check. Maybe you should add that code. I'm pretty sure the way you print causes the segfault. Show a [mcve] – Jabberwocky Jul 27 '21 at 09:17
  • Your code is correct. Post a [mcve] that is the **exact** code you compile and run. Also are you sure the code run is _actually_ the code you compile? – Jabberwocky Jul 27 '21 at 09:54

4 Answers4

1

When you malloc within foo, the dereference now points to the value malloced within the function's scope. This means that the value within the function is changed and not the value outside of the function. To correct this, you don't need to malloc within the function to change the value of check:

void foo (int *check) {
    *check= 9;
}

void main () {
    int check = 5;
    foo(&check); // check is now 9
}
PotatoParser
  • 1,008
  • 7
  • 19
  • In this case, I am getting this error: Segmentation fault (core dumped). I am assuming this occurs when dereferencing line executed. – helloword Jul 27 '21 at 09:07
  • @helloword this code is correct. There is something else you are doing wrong. Maybe ask a new question about this exact issue. – Jabberwocky Jul 27 '21 at 09:13
0

You are doing everything just fine, the only thing that is wrong is trying to malloc the variable you passed to the function , since it is already allocated on stack. In order to do what you're trying to do, you should declare the integer as pointer to integer (int *check) outside the function, and avoid using the & character when calling the function with the pointer as parameter.

Nastor
  • 638
  • 4
  • 15
  • 1
    Why would the OP want to define `check` as a pointer? There is no need for that. – Gerhardh Jul 27 '21 at 09:01
  • It seems to me he's trying to learn how to dynamically allocate memory, otherwise he wouldn't have (wrongfully) called the malloc function. – Nastor Jul 27 '21 at 09:02
  • 1
    Maybe, maybe not. There is no indication about the purpose of the code. – Gerhardh Jul 27 '21 at 09:03
0

You passed the variable check to the function foo by reference through a pointer to it

int check=5;
foo(&check);

So dereferencing the pointer you could get a direct access to the variable check and could change it like

*check= 9;

However within the function you reassigned the pointer with a new address of a dynamically allocated memory

check=  malloc(sizeof(int));

So now the pointer check doe not point to the original object passed to the function by reference. As a result this statement

*check= 9;

changes the dynamically allocated object of the type int instead of changing the variable passed to the function by reference.

Edit: malloc is deleted now it gives me Segmentation fault (core dumped) error

It is a bad idea to change such dramatically the code in the question because it will only confuse readers of the question and answers. Neither segmentation fault should occur. It seems the new provided code in the question does not correspond to the actual code that generates a segmentation fault.

Here is a demonstrative program. It compiles and runs successfully.

#include <stdio.h>

void foo ( int *check )
{
    *check = 9;
    printf( "Inside foo check = %d\n", *check );
}

int main(void) 
{
    int check = 5;
    
    printf( "Before foo check = %d\n", check );
    
    foo( &check );
    
    printf( "After  foo check = %d\n", check );

    return 0;
}

The program output is

Before foo check = 5
Inside foo check = 9
After  foo check = 9
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

To change a variable through a function you need to pass it by reference, not value. Your title and code do not match.

Here is a version with both kinds of arguments, side by side:

#include <stdio.h>

int foo(int *ref, int val) {
    *ref = 1122;                   // by reference
    val = 1155;                    // by value
    printf("inside:\n%d %d\n", *ref, val);
    return val;                    // otherwise "val=1155" is lost
}
int main(void) {
    int ree = 12;         // "referencee"
    int v = 15;

    printf("main:\n%d\n", foo(&ree, v));    // return value (1155)
    printf("%d %d\n", ree, v);              // 1122 and 15

}

ree is passed as &ree to ref; this address/pointer gets dereferenced inside the function with *ref to change ree's value.