Assign memory in child function
Hi All,
I have some problem in assign memory for the pointer type. My example code in below: void test(char *kk) { kk = malloc (sizeof(char*) + 10); strcpy(kk,"abcdef"); printf("Value of kk inside test(): %s\n",kk); } int main() { char *kk; test(kk); printf("Value of kk at main: %s\n",kk); return 0; } when run: Value of kk inside test: abcdef Memory fault (core dumped) Why I get "Memory fault" message. I think when exit out of test() function the memory have been assigned will be release right? If true. How to serve this problem. My requirement is: assign memory inside the child function and can get back at main when exit the child fucntion. Please help me this problem. Thank you so much. James |
The problem is that you're only changing the value of kk inside the function. Try passing a pointer to kk to your test() function instead:
Code:
void test(char **kk) Code:
int set_it(int num) |
You wrong! I have done brfore you reply (like you say) but the result is still the same. Have you another way to serve this.
Thank you for reply. |
Umm...no, I'm not wrong:
Code:
#include <stdio.h> |
Oh!!!! Sorry I have a mistake before. Yes! you right!. But have you another way if only accept a char's pointer (not array of char pointer) argument at test function. Mean test function not change test(char *kk)?
Thank you very much. |
Quote:
Code:
void test(char *kk) |
Uh... I hope you don't seriously want him to do that :-)
While at it, I recommend changing the memory allocation line Code:
char *pStr = (char*)malloc (sizeof(char*) + 10); Code:
char *pStr = (char*)malloc (10*sizeof(char)); Groetjes, Kees-Jan |
Quote:
Aiza |
All times are GMT -5. The time now is 12:01 PM. |