Value of n sets to 0 or 1 (undefined behavior) while I'm trying to learn use of realloc and malloc

Advertisements I’m working on a C program to create an interactive interface for a dynamic array of strings. The program is menu-driven and follows these steps: Asks the user for the initial length of the array. Stores corresponding strings into a dynamic array initialized with that length. Initiates a loop of the menu, prompting the… Read More Value of n sets to 0 or 1 (undefined behavior) while I'm trying to learn use of realloc and malloc

Error during memory reallocation inside a function

Advertisements I wrote a function to append pointer to an object to array, but realloc can’t properly reallocate memory when it’s called from a nested function. However, when I’m reallocating memory from function, where object has been previously allocated, everything is alright Here is a simplified example of my code: #include <stdlib.h> typedef struct Node… Read More Error during memory reallocation inside a function

c stack (using dynamic array) realloc memory leak problem

Advertisements #include <stdio.h> #include <stdlib.h> int LENGTH = 1; int TOP = -1; void push(char**, char); char pop(char*); char peek(char*); int isEmpty(); int isFull(); void convertToRPN(char*, char*, char*); int isOperator(char); int getPrecedence(char); int main(void) { char* stack = (char*) malloc(sizeof(char) * LENGTH); if (!stack) { printf("Memory allocation failed./n"); exit(1); } char expression[100]; printf("Enter the mathematical… Read More c stack (using dynamic array) realloc memory leak problem

Undefined Behavior on inner realloc()

Advertisements I’m attempting to write a PE parser, and my program contains two loops as shown below: size_t i = 0; while (condition_1) { struct _IMAGE_IMPORT_DESCRIPTOR64 *importDescriptorArray = malloc(sizeof(struct _IMAGE_IMPORT_DESCRIPTOR64)); struct _IMAGE_THUNK_DATA64 *originalFirstThunkArray = malloc(sizeof(struct _IMAGE_THUNK_DATA64)); size_t originalFirstThunkArrayIndex = 0; originalFirstThunkArray[originalFirstThunkArrayIndex].u1.ordinal = some_value; //set to a computed value while (condition_2) { originalFirstThunkArrayIndex++; originalFirstThunkArray = realloc(originalFirstThunkArray,… Read More Undefined Behavior on inner realloc()

Confusion about using malloc/calloc pointer to hold the return value of realloc

Advertisements Someone said that using the original malloc()/calloc() pointer as the variable that holds the return value of realloc() is wrong. Here is an example: #include <stdlib.h> int main() { int *malloc_ptr = malloc(5 * sizeof(int)); malloc_ptr = realloc(malloc_ptr, 10 * sizeof(int)); return 0; } Their reasoning was that if realloc() failed it would return… Read More Confusion about using malloc/calloc pointer to hold the return value of realloc