I'm new to C, coming from another language and I'm getting this error that I understand now but couldn't find how to fix it inside of my code.
It's pretty simple but even when debugging with printf or perror I couldn't figure it out because it returns Success on the memory allocation.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
char *tasks[6];
// Made the size 5 to allow for `\0`
tasks[0] = (char *) malloc(5 * sizeof(char));
tasks[1] = (char *) malloc(5 * sizeof(char));
tasks[2] = (char *) malloc(5 * sizeof(char));
tasks[3] = (char *) malloc(5 * sizeof(char));
tasks[4] = (char *) malloc(5 * sizeof(char));
tasks[5] = (char *) malloc(5 * sizeof(char));
for (int i = 0; i < sizeof(tasks); i++) {
if (!tasks[i]) {
perror("malloc result : "); // Returns Success
}
}
strncpy(tasks[0], "Dish", 5);
strncpy(tasks[1], "Laun", 5);
strncpy(tasks[2], "Bath", 5);
strncpy(tasks[3], "Flor", 5);
strncpy(tasks[4], "Tras", 5);
strncpy(tasks[5], "Offi", 5);
for (int i = 0; i < sizeof(tasks); i++) {
printf("%s\n", tasks[i]);
}
for (int i = 0; i < sizeof(tasks); i++) {
free(tasks[i]);
}
sizeofis in bytes, not in number of items (which are pointers, so 4 or 8 bytes long)#define TASKS_SIZE 6and then only ever use that one when referring to the size of the array. The root cause of the bug is "magic numbers" in combination of misunderstanding how sizeof works.mallocto seterrno; I was just pointing out that these common implementations of the Standard Library do set it.