I am just starting out with C and was writing a simple program which requires me to intinalize array in different way. So I am using pointers and malloc to allocate the dynamic pointer. However, this pointer is getting deallocated or returns to its original value as soon as the input function finishes. Here is the simplified code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_arr(char *arr, int len, char *msg) {
printf("%s Array: ", msg);
for(int i = 0; i < len; ++i) {
printf("%c ", arr[i]);
}
}
void input_arrs(char *num_arr, char *alpha_arr, char *alpha_num_arr, int *num_arr_len, int *alpha_arr_len, int *alpha_num_arr_len) {
int choice;
printf("Input Options:\n");
printf("0. Normal Case\n");
printf("1. Exceptional Case\n");
printf("Choice: ");
scanf("%d", &choice);
switch (choice) {
case 0: {
char default_num_arr[5] = {'5', '7', '3', '7', '5'};
*num_arr_len = 5;
num_arr = (char*) malloc(sizeof(default_num_arr));
memcpy(num_arr, default_num_arr, sizeof(default_num_arr));
print_arr(num_arr, *num_arr_len, "Number");
break;
}
case 1:
// Something
break;
case 2:
// Something
break;
default:
printf("Unknown Choice");
exit(0);
break;
}
print_arr(num_arr, *num_arr_len, "Number");
// num_arr seems to be freed here
}
int main() {
int num_arr_len;
char *num_arr;
input_arrs(num_arr, &num_arr_len);
// Shows garbage value here
print_arr(num_arr, num_arr_len, "Number");
}
I also tried using memmove and simple for loops to check if the problem was with memcpy but that doesn't seem to be the case.