0

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.

Ayush Singh
  • 1,159
  • 3
  • 15
  • 28
  • Parameters are always passed by value in `C`. You pass the (uninitialized) value of the `main` variable `num_arr` to the function `input_chars`. The function gets a copy of the pointer. This copy is overwritten with the return value of `malloc`. But since you passed the ''value'' of `num_arr`, the variable itself can't be changed inside the function. Therefore you still use the (uninitialized) variable in `main`. BTW: the memory is not freed. – harper Jun 07 '21 at 11:04

0 Answers0