0
void allocateMemory(char* pString, int length) { 
    pString = (char*)malloc(length); 
} 

void test() { 
    char* pString = NULL; 
    allocateMemory(pString, 20); 
    strcpy(pString, "Hello world."); 
} 

Why does this program crash? I have allocated memory using malloc. When the function returns I would expect that pString points to a memory on the heap? Isn't this what is happening? Seems like pString still points to null?

Can't we change the address to what a pointer points to?

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Angelo
  • 61
  • 1
  • 8
  • [This question](http://stackoverflow.com/q/22748603/1233508) might explain what's going on - the pointer is passed *by value*, so changes made in the function affect only the new copy of the value, not the original value. – DCoder Sep 13 '14 at 15:53

2 Answers2

3

in C, it should be something like

void allocateMemory(char** pString, int length) { 
    *pString = (char*)malloc(length); 
}

void test() { 
    char* pString = NULL; 
    allocateMemory(&pString, 20); 
    strcpy(pString, "Hello world."); 
} 
Jarod42
  • 190,553
  • 13
  • 166
  • 271
  • But I want to understand what is happening in the previous code. I understand what you are doing is passing a pointer address and having a pointer to a pointer accept it. However what is happening in the previous case? – Angelo Sep 13 '14 at 15:45
  • @zeloran: in your case, you pass the pointer by value, so you only modify the parameter (you would be able to modify the content of the pointed data if applicable), not the original pointer. – Jarod42 Sep 13 '14 at 15:50
  • So when the function call returns it is still NULL? – Angelo Sep 13 '14 at 15:52
  • @zeloran: yes, your `pString` of `test()` is never modified. and you so call `strcpy(NULL, "Hello world");` which invoke UB and may crash your application. – Jarod42 Sep 13 '14 at 15:59
0

In your code you are passing pString using pass by value method, so the content of pString that is NULL is getting passed.

Daemon
  • 1,419
  • 1
  • 17
  • 34
  • Thanks Gaurav. But in the allocatememory function the pointer returned by malloc is assigned to NULL? So does that contain an actual value or a NULL? I am confused by this. – Angelo Sep 13 '14 at 15:56
  • pString in allocatememory() is different variable from what you are passing from test(). So memory allocated in allocatememory() can be used in that function only. While in test() pString still holds NULL. – Daemon Sep 13 '14 at 15:59
  • To understand it properly print address of pString in both the function and you will come to know. – Daemon Sep 13 '14 at 16:03
  • Ok Gaurav will try that. In the fucntion print it before or after the malloc? – Angelo Sep 13 '14 at 16:06
  • @zeloran: *the address* of `pString` doesn't change after `malloc`, only its *value* does. – DCoder Sep 13 '14 at 16:47