How do malloc() and free() work?

OK some answers about malloc were already posted. The more interesting part is how free works (and in this direction, malloc too can be understood better). In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will get … Read more

Do I cast the result of malloc?

TL;DR int *sieve = (int *) malloc(sizeof(int) * length); has two problems. The cast and that you’re using the type instead of variable as argument for sizeof. Instead, do like this: int *sieve = malloc(sizeof *sieve * length); Long version No; you don’t cast the result, since: It is unnecessary, as void * is automatically … Read more

Why this program is crashing?

What yo actually do is called “undefined behavior”. You allocate 4 bytes and then store into that buffer integers. It works fine for the first integer (or maybe two if sizeof(int)==2 on your machine) but for the next integer the behavior becomes undefined. It may segfault immediately and it may take more similar stores until … Read more

convert static_castmalloc/free to new/delete

Just do char* only_valid_data = new char[data_size]; to allocate. To free you do delete[] only_valid_data; Important note: When you allocate memory with new it will allocate data_size elements, not data_size bytes (like malloc does). The size of an element is the size of the non-pointer base type, in your case e.g. sizeof(*only_valid_data). In this case … Read more

Malloc , Realloc , Memset : Struct pointers , arrays of char, int

Error was in v_push_back implementation : v->e_array = check_a(memcpy((void*)((char*)v->e_array + (v->no_e * v->e_sz)) ,new_val, v->e_sz)); //pointer has not to be saved check_a(memcpy((void*)((char*)v->e_array + (v->no_e * v->e_sz)) ,new_val, v->e_sz)); Because memcpy returns a pointer , in this case, to the last element of the array so we would have lost access to all previous memory

Segmentation fault, I don’t know why

I would recommend you to replace if(c!=’ ‘ && c!=’\t’ && c!=’\n’) with if(!isspace(c)) // Iam easier and more readable from ctype.h. Which detects all these characters ‘ ‘ space ‘\t’ horizontal tab ‘\n’ newline ‘\v’ vertical tab ‘\f’ feed ‘\r’ carriage return Also you should change char*** word_array; (three star general) to pointer to … Read more