I've been learning C for a few weeks. I have solved my problem by using malloc()
to allocate some memory on the heap. I have an inkling about why my code failed but I'm not 100% sure. Unfortunately I am self-teaching so I have to turn to you kind people on the internet.
Code description Calls a function getString()
which declares an array, fills the array using the inbuilt getchar()
and returns a pointer to that array.
The issue I print the returned pointer value and everything is fine. BUT when I pass it to another function that simply spits it back out and try to print that, the end of the string is cut off, sometimes it spits out a nonsense character.
What I think could be happening The original array is only in use for as long as the getString() function & so C is using some of the memory in the array address to store other things.
Is my intuition correct? If not, could someone point me in the right direction?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 100
char * getString(void);
char * doSomethingWith(char *);
int main(void)
{
char *string1 = getString();
printf("String: %s\n", string1);
char *string2 = doSomethingWith(string1);
printf("String: %s\n", string2); // This print out is unreliable!
return EXIT_SUCCESS;
}
char * getString(void) {
int c;
char arr[MAXLEN];
char *string = arr;
char *cur = arr;
while((c = getchar()) != '\n' && c != EOF) {
if(cur - string < MAXLEN - 2) {
*cur++ = c;
}
}
*cur = '\0'; // Terminate string
return string;
}
char * doSomethingWith(char *string) {
return string;
}
Here is my amended getString() which behaves correctly.
char * getString(void) {
int c;
char *string = malloc(sizeof *string * MAXLEN);
char *cur = string;
while((c = getchar()) != '\n' && c != EOF) {
if(cur - string < MAXLEN - 2) {
*cur++ = c;
}
}
*cur = '\0'; // Terminate string
return string;
}
Update: Thanks for all the answers! Very much appreciated.