I'm trying to write a little program which uses realloc(), getchar() and some pointer arithmetic to store an array of characters in the memory.
I have a function called "inputArray" (in convert.c) which receives a pointer to a char (which is NULL to begin with, declared in main.c), then gets reallocated with one char until getchar() gets a '\n' char. the functions seems to work ok, but then when I try to print the string back in main.c, i get a "segmentation fault (core dumped)" error. I've been looking for hours, can't find where the problem is. Thanks!
main.c:
# include "convert.h"
int main()
{
char * string = NULL;
inputArray(string);
printf("%s", string);
free(string);
return 0;
}
convert.c:
#include "convert.h"
void inputArray(char * array)
{
/*pointer to the array*/
char * ptr = NULL;
/*stores the char*/
char c = 0;
/*counter used for pointer arithmetic*/
int count = 0;
/*loop for getting chars in array*/
while ((c = getchar()) != '\n')
{
array = realloc(array, sizeof(char));
ptr = array + count;
*ptr = c;
++count;
}
/*add the null char to the end of the string*/
array = realloc(array, sizeof(char));
ptr += count;
*ptr = '\0';
}
convert.h:
#include <stdio.h>
#include <stdlib.h>
void inputArray(char * array);
The size of the new allocated array is incorrect. You have to allocate count + 1
characters.
array = realloc(array, ( count + 1 ) * sizeof(char));
Take into account that it is more safe to use a temporary pointer to reallocate the memory. Otherwise the original address of the previously allocated memory will be lost.
Also these statements
array = realloc(array, sizeof(char));
ptr += count;
are wrong. You should at least write
array = realloc(array, count * sizeof(char));
ptr = array + count - 1;
Also the function should be declared like
char * inputArray(char * array);
and it must to return the new pointer to the caller.
And in main you have to write
string = inputArray(string);
Otherwise the function should accept the argument by reference that is the parameter should be declared like
void inputArray(char ** array);
and be processed correspondingly in the function.