割り振りが正常に行われたことを確認してから参照を使用します。
割り振りが失敗すると、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 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);
}
|
|