This is a project that gets a string from user and prints how many vowels and constants the string has. The problem started when i created the fanctions malloc_memory and free_memory for more clear code so i can call the functions inside main and not allocating memory and free memory directly in main function. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define E_A_LETTERS 26
#define MAX_LENGTH 50
int check_vowels(char *p_string);
void malloc_memory(char **p_string);
void free_memory(char *p_string);
int main(void){
// Here your code !
char *string;
int vowels;
int constants;
malloc_memory(&string);
printf("Enter a string: ");
fgets(string, MAX_LENGTH, stdin);
vowels = check_vowels(string);
constants = strlen(string) - vowels;
printf("\nNumber of vowels : %d", vowels);
printf("\nNumber of constants : %d\n", constants);
free_memory(string);
}
int check_vowels(char *p_string)
{
int i = 0;
int count = 0;
while(1)
{
if(*(p_string + i) == 'A' || *(p_string + i) == 'E' || *(p_string + i) == 'I' || *(p_string + i) == 'O' || *(p_string + i) == 'U')
count++;
if(*(p_string + i) == 'a' || *(p_string + i) == 'e' || *(p_string + i) == 'i' || *(p_string + i) == 'o' || *(p_string + i) == 'u')
count ++;
if(*(p_string + i) == '\0')
break;
i++;
}
return count;
}
void malloc_memory(char **p_string)
{
p_string = (char **)malloc(MAX_LENGTH * sizeof(char) + 1);
if(p_string == NULL)
{
printf("Unable to allocate memory...");
exit(0);
}
}
void free_memory(char *p_string)
{
free(p_string);
}
And i am getting this output - error :
Enter a string: This is a string
Number of vowels : 4
Number of constants : 12
Segmentation fault (core dumped)