Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic memory created inside a function [duplicate]

Tags:

c

pointers

I would like to know the technical reason(in terms of memory) why this piece of code will not work:

#include <stdio.h>
#include <stdlib.h>

int* fun(int*);
int main()
{
  int a=5;
  int* ptr;
  //  ptr=(int*)malloc(sizeof(int));
  fun(ptr);
  a=*ptr;

  printf("\n the val of a is:%d",a);
  return 0;
}

void fun(int* ptr)
{

  ptr = (int*)malloc(sizeof(int));
  *ptr = 115;


}

Why will this not work? I thought that the heap(more importantly the addresses) is common to all the function's variables in the stack .

Also, why would this work. If i comment the memory allocation inside the function fun and uncomment the one in main . It works fine.

like image 813
tomkaith13 Avatar asked Dec 14 '09 09:12

tomkaith13


1 Answers

In C, everything is passed by value.

What you are passing to fun() is a copy of the pointer you have in main().

That means the copy of ptr is aimed at the allocated memory, and that memory set to 115.

The ptr in main() still points at an undefined location because it has never been assigned.

Try passing a pointer to the pointer, so that within fun() you have access to the pointer itself:

#include <stdio.h>
#include <stdlib.h>

int* fun(int**); // <<-- CHANGE
int main()
{
    int a=5;
    int* ptr;
    //  ptr=(int*)malloc(sizeof(int));
    fun(&ptr); // <<-- CHANGE
    a=*ptr;

    printf("\n the val of a is:%d",a);
    return 0;
}

int* fun(int** another_ptr) // <<-- CHANGE
{

    *another_ptr = (int*)malloc(sizeof(int)); // <<-- CHANGE
    **another_ptr = 115; // <<-- CHANGE
    return *another_ptr;
}

The other option would be to make fun() actually return the updated pointer (as advertised), and assign this to ptr:

#include <stdio.h>
#include <stdlib.h>

int* fun(int*);
int main()
{
    int a=5;
    int* ptr;
    //  ptr=(int*)malloc(sizeof(int));
    ptr = fun(ptr); // <<-- CHANGE
    a=*ptr;

    printf("\n the val of a is:%d",a);
    return 0;
}

int* fun(int* another_ptr)
{
    another_ptr = (int*)malloc(sizeof(int));
    *another_ptr = 115;
    return another_ptr; // <<-- CHANGE
}

Edit: I renamed the variable in fun() to make it clear that it is different from the one you use in main(). Same name doesn't mean anything here.

like image 68
DevSolar Avatar answered Oct 21 '22 15:10

DevSolar