Check your allocations again.
Your first loop - where you allocate - is using loop variable a.
However, you assign the memory blocks using variable i (always=0).
All allocations will then be assigned to the first entry in the array,
resulting in a memory leak.
The second loop will then try to free u ninitialized pointers.
By the way - why loop backwards on 'a' and then look up using 'index-a'.
/Per W
On Thu, 2 Nov 2006, Daniel Yan wrote:
> Hi, all,
>
> I met a problem when I free an array of points. The source code is as
> following:
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
>
> char *http_parampos[255] = { "name=rule1",
> "protocol=tcp",
> "sourip=172.16.12.53",
> "sourport=3256",
> "desip=172.16.12.98",
> "desport=9685",
> };
>
> int main(void)
> {
> int a = 5;
> int i = 0;
> char *value[7];
> char param_name[40];
> char *param_value;
> int index = 5;
>
> for (;a >= 0;a--)
> {
> strncpy(param_name, http_parampos[index - a], sizeof(param_name));
> param_value = strchr(param_name,'=');
> if (param_value)
> {
> *param_value = '\0';
> param_value++;
>
> value[i] = malloc(sizeof(param_value)+1);
> strcpy(value[i], param_value);
> printf("value[%d] = %s\n", i, value[i]);
> //free(value[i]);
> }
> i++;
> }
>
> value[6] = 0;
> i = 0;
>
> printf("come to error!\n");
>
> for(i = 0; i < 6; i++)
> {
> free(value[i]);
> }
>
> getch();
> return 0;
> }
>
> When I tried to free the memory, it breaks down. I have tried these code
> with gcc and it works. And if I free the memory just after I malloc the
> memory(see the coments line), it also works.Could anyone tell me what was
> wrong with my codes?
> Thanks in advance.
>
> BR,
> Daniel
>
|