I'm trying to dynamically allocate memory to a struct using the user's input as the size but every time I do it I get a segerror.
my struct is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// structure that holds the info for a phone record
struct PHONE_RECORD {
char name[50];
char birthday[12];
char phone[15];
} *phonebook;
and the code for dynamically allocating it is here:
int num_space(){
int num_records;
struct PHONE_RECORD *phonebook;
printf("Enter num of records: ");
scanf("%d", &num_records);
phonebook = (struct PHONE_RECORD*) malloc(sizeof(struct PHONE_RECORD)*num_records);
if (phonebook == NULL){
printf("Not enough memory.\n");
return 1;
}
free(phonebook);
return num_records;
}
The code allows the user to type in a number but then gives me a segerror and exits the program. There are other parts in this project but I have tested them all and they work without issue its only the malloc part that doesn't work. For reference here is my main:
#include <stdio.h>
#include <string.h>
#include "mini4Bphone.c"
extern void addRecord();
extern void findRecords();
extern void listRecords();
extern void loadCSV();
extern void saveCSV();
extern int num_space();
// dispaly the menu
void menu() {
int choice;
num_space();
//display unitl user quits using while loop and execute whatever command user inputs
while (1) {
printf("Phonebook Menu: ");
printf("(1) Add ");
printf("(2) Find ");
printf("(3) List ");
printf("(4) Quit ");
printf("> ");
scanf("%d", &choice);
switch (choice) {
case 1:
addRecord();
break;
case 2:
findRecord();
break;
case 3:
listRecords();
break;
case 4:
return;
default:
printf("Invalid choice.\n");
break;
}
}
}
// load tne csv,menu and save the csv after all wanted functions are complete, return 0
int main() {
loadCSV();
menu();
saveCSV();
return 0;
}
Thanks for any input its appreciated!
I tried using malloc inside and outside a function to no avail. It's supposed to et the user input a number and then allocate the space to the struct. However, every time I tried to run the program I get a segerror.