NO

Author Topic: Allocation problem  (Read 2884 times)

Elpower

  • Guest
Allocation problem
« on: June 04, 2012, 04:24:33 pm »
Code: [Select]
TextFromWindow(GetDlgItem(hwnd, EDITAR_ED_OBSERVACOES), backup_ficha->observacoes);
...
int TextFromWindow(HWND hwnd, char * text)
{
int size = GetWindowTextLength(hwnd)+1;

text = malloc(size);
GetWindowText(hwnd, text, size);
return size;
}

At "text = malloc(size);" memory is allocated to text but in "GetWindowText(hwnd, text, size-1);" text lose the allocation.
I don't know what is wrong.

Offline DMac

  • Member
  • *
  • Posts: 259
Re: Allocation problem
« Reply #1 on: June 04, 2012, 05:25:49 pm »
Arguments in C are always by value.  In your snippet you declare a pointer to char.  Good.  You pass that pointer to char to your function as an argument.  Inside the function the argument is a copy of your pointer and so the copy receives the address of the allocated memory and is filled with text.  Unfortunately the original pointer does not and so you don't see the data outside of the function.

What you need to do is declare a pointer to char and then pass the address of that pointer to the function.  Then in the function you have a copy of the address of the pointer to char.  This then you dereference and you have the original pointer that will receive the allocation and data.

Code: [Select]
TextFromWindow(GetDlgItem(hwnd, EDITAR_ED_OBSERVACOES), &backup_ficha->observacoes);
...
int TextFromWindow(HWND hwnd, char **text)
{
int size = GetWindowTextLength(hwnd)+1;

*text = malloc(size);
GetWindowText(hwnd, *text, size);
return size;
}
No one cares how much you know,
until they know how much you care.

Elpower

  • Guest
Re: Allocation problem
« Reply #2 on: June 04, 2012, 06:27:33 pm »
Sorry, i have correct the problem after post but thanks.