alloc_buffer - 1Fr3aK2/Cub3d GitHub Wiki

📝 alloc_buffer

Allocates and fills the map buffer by reading lines from the map file. Each line is trimmed and stored in the buffer array. Handles memory allocation errors and file reading errors.

⚙️ Parameters

Parameter Type Description
data t_data * Pointer to the main data structure containing file descriptor and map buffer. Must be non-NULL.
i int * Pointer to the current index in the buffer where the line should be stored.

🔁 Returns

Return value Description
1 Lines successfully read and stored in the buffer.
-1 Invalid input (data is NULL).

📖 Description

The alloc_buffer function performs the following steps:

  1. Validates that data is non-NULL. If not, returns -1.
  2. Reads lines from the map file using get_next_line.
  3. For each line, if the current index *i is less than the map height:
    • Trims the newline character from the line using ft_strtrim.
    • Stores the trimmed string in data->map.buffer[*i].
    • Frees the original line memory.
  4. Handles allocation failures or read errors by calling exit_error with an appropriate error message.
  5. Increments the index *i after processing each line.
  6. Returns 1 when all lines are successfully stored in the buffer.

💡 Example Usage

t_data data;
int i = 0;

if (alloc_buffer(&data, &i) == -1)
{
    printf("Error: invalid data structure.\n");
}