-2

I'm trying to understand how passing pointers to functions work, but I don't understand the following situation : Why this code work

void setVar(uint32_t* var) {
    *var = 10;
} 

int main() {
    uint32_t myVar = 0;
    setVar(&myVar);

    return 0;
}

and this one lead to a runtime error ? :

void setVar(uint32_t* var) {
    *var = 10;
} 

int main() {
    uint32_t* myVar = 0;
    setVar(myVar);

    return 0;
}

I'd appreciate your answers.

AyoubS
  • 51
  • 8
  • Because you dereference a null pointer. Also you no allocated memory for the the function to write in. – Kami Kaze May 10 '21 at 14:34
  • 3
    That is because `uint32_t* myVar = 0;` initializes `myVar` to `NULL`, not `* myVar` – Gerhardh May 10 '21 at 14:35
  • since you are initializing uint32_t pointer (myVar) to 0 you are saying that you store memory address into myVar and when you dereference it you you are trying to set memory address 0 to 10 what you want to do is ```uint32_t myVar = 10;uint32_t* pointer = &myVar;``` and pass pointer to your function – VictorJimenez99 May 10 '21 at 14:37
  • related: https://stackoverflow.com/questions/4955198/what-does-dereferencing-a-pointer-mean – Kami Kaze May 10 '21 at 14:38
  • Ask yourself this question: where does `myVar` point? – Jabberwocky May 10 '21 at 14:38
  • 1
    related: https://stackoverflow.com/questions/2094666/pointers-in-c-when-to-use-the-ampersand-and-the-asterisk/2094715#2094715 – Kami Kaze May 10 '21 at 14:40
  • Does this answer your question? [What EXACTLY is meant by "de-referencing a NULL pointer"?](https://stackoverflow.com/questions/4007268/what-exactly-is-meant-by-de-referencing-a-null-pointer) – cigien May 10 '21 at 22:38

1 Answers1

1

The issue is not the pointer. The issue is that you initialize the pointer you pass to the function with 0 (uint32_t* myVar = 0;) and then dereference it in your function (*var = 10;), which is disallowed. You should make sure, the pointer that is passed is not a NULL pointer, either do that within the function or make sure that function only ever is called with valid parameters.

lulle2007200
  • 888
  • 9
  • 20