Compruebe que la asignación haya sido
satisfactoria antes de utilizar la referencia. malloc() devolverá NULL si la asignación
falla.
struct structure {
unsigned int len;
unsigned char *ptr;
};
void function(struct structure *s)
{
char type = 'c';
s->len = 2;
s->ptr = (unsigned char *) malloc(s->len + 1);
if (!s->ptr) {
fprintf(stderr, "Malloc failure: unable to allocate memory.");
exit(EXIT_FAILURE);
}
strcpy((char *)s->ptr + 1, "st");
s->ptr[0] = type;
free(s->ptr);
}
void foo(){
char *character = (char *) malloc(5 * sizeof(char));
if (NULL == character) {
fprintf(stderr, "Malloc failure: unable to allocate memory.");
exit(EXIT_FAILURE);
}
strcpy(character, "st");
free(character);
}
|
|