I am having an issue with dynamic arrays and malloc
. I am fairly new to C so please excuse (and advise on) any rookie mistakes.
The problem is I create an array (input_string in this case) and pass it to func2
. Then in func2
I do a test, print out the first element of input_string.
This works as expected in the first printout before the malloc
, but after the malloc
it doesn't print anything. This seems weird to me since in between the to printf
statements I do nothing to the input_string.
I'm assuming that I am dealing with these arrays incorrectly, but I'm unsure.
Here is a snippet of the code in question:
Updated
... // includes not in snippet
/* CONSTANTS */
#define LINE_LEN 80
/* Function declarations */
char* func1(void);
char* func2(int tl, char* input_string);
int main(void) {
char* input_string;
int tab_length;
char* output_string;
input_string = func1();
output_string = func2(tl, input_string);
return 0;
}
char* func1(void) {
char cur_char;
char* input_ptr;
char input_string[LINE_LEN];
while ((cur_char = getchar()) != '\n' && chars_read < 80) {
// iterate and create the array here
}
input_ptr = &input_string[0]; /* set pointer to address of 0th index */
return input_ptr;
}
char* func2(int tl, char* input_string) {
int n = 0, output_idx = 0;
char* output_ptr;
printf("\nBefore malloc: %c ", *(input_string));
output_ptr = malloc(tab_length * chars_read+1);
if (output_ptr == NULL) {
printf("Failed to allocate memory for output_ptr.\nExiting");
exit(1);
}
printf("\nAfter malloc: %c ", *(input_string));
...
return output_ptr;
}
P.s.: Any undeclared variables have been declared outside of this snippet of code.
Update
Thanks for all the replies and advice. It is very much appreciated.