0

I've got the following piece of code. I got a pointer from the function and keep it in array of char pointers. Everything looks OK however when I try to print from main function array[0] it prints some symbols but not what I need. I use now memory allocation in the function as advised however still not there

Many thanks

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



char *getIn();


int main(void)
{
  char *array[3];

  array[0] = getIn();
  array[1] = getIn();
  array[2] = getIn();

  printf("%s\n", array[0]);


  return 0;
}

char* getIn()
{
   char *p;
   char input[30];

printf("Please enter something: ");
fgets(input, 20, stdin);

input[strlen(input) - 1] = '\0';

p = (char *) malloc(sizeof(char));
p = input;
return p;

}

Max_S
  • 135
  • 1
  • 1
  • 9
  • You return a reference to local variable `input`. – KiaMorot Feb 04 '15 at 09:04
  • `p = &input[0];` Although Returns the local address is invalid when the local address is outside the scope. – BLUEPIXY Feb 04 '15 at 09:04
  • You're returning a pointer to a local array (`input[]`), goes out of scope (i.e. becomes invalid) when you return from `getIn()`. – Paul R Feb 04 '15 at 09:05
  • thanks guys. I added malloc however it still doesn't work... – Max_S Feb 04 '15 at 09:24
  • That is because `input[]` is on the stack and the stack frame is destroyed on return from the function, no matter what you try to do with another pointer. You can try `static char input[30];` and remove the `malloc()` business (which causes a memory leak anyway). – Weather Vane Feb 04 '15 at 10:26
  • I thought malloc creates memory on the heap. This way I can pass pointer to this memory – Max_S Feb 04 '15 at 10:28
  • You allocated memory for 1 byte and then discarded it by re-assigning `p`. – Weather Vane Feb 04 '15 at 10:29

0 Answers0