Проверить, успешно ли выполнено выделение памяти, прежде чем использовать данную ссылку. В случае неудачи операция malloc() возвратит NULL.
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: не удалось выделить память.");
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: не удалось выделить память.");
exit(EXIT_FAILURE);
}
strcpy(character, "st");
free(character);
}
|
|