C
Capstar
Hi NG,
I'm trying to allocate some resources, in this example a structure, with
containing a buffer. When a allocation failes, all previous allocations
need to be freed. When I try to compile it I get the next warning:
resource-loop.c:38: warning: deprecated use of label at end of compound
statement
Is there a better way of doing this?
Or is this guaranteed to work anyway?
#include <stdlib.h>
#include <stdio.h>
struct foo
{
char *bar;
};
int main(void)
{
int i;
struct foo* array[6];
for(i = 0; i < 6; ++i)
{
if(!(array = malloc(sizeof *array)))
{
fprintf(stderr, "Unable to allocate foo%d\n", i);
goto err_malloc_foo;
}
if(!(array->bar = malloc(1024)))
{
fprintf(stderr, "Unable to allocate bar%d\n", i);
goto err_malloc_bar;
}
}
return EXIT_SUCCESS;
for(; i >= 0; --i)
{
free(array->bar);
err_malloc_bar:
free(array);
err_malloc_foo:
}
return EXIT_FAILURE;
}
Mark
I'm trying to allocate some resources, in this example a structure, with
containing a buffer. When a allocation failes, all previous allocations
need to be freed. When I try to compile it I get the next warning:
resource-loop.c:38: warning: deprecated use of label at end of compound
statement
Is there a better way of doing this?
Or is this guaranteed to work anyway?
#include <stdlib.h>
#include <stdio.h>
struct foo
{
char *bar;
};
int main(void)
{
int i;
struct foo* array[6];
for(i = 0; i < 6; ++i)
{
if(!(array = malloc(sizeof *array)))
{
fprintf(stderr, "Unable to allocate foo%d\n", i);
goto err_malloc_foo;
}
if(!(array->bar = malloc(1024)))
{
fprintf(stderr, "Unable to allocate bar%d\n", i);
goto err_malloc_bar;
}
}
return EXIT_SUCCESS;
for(; i >= 0; --i)
{
free(array->bar);
err_malloc_bar:
free(array);
err_malloc_foo:
}
return EXIT_FAILURE;
}
Mark