0

I need to input some string in function with prototype char* () and print that string in main function but I can menage to do that. I'm a begginer in c programing.

I try this:

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


char* read_data();

int main()
{
    char str[100];
    char *p_str;

    p_str=read_data();

   
    printf("entered string is: %s and pointer on that string is %p \n",p_str,p_str);
//print from here is a problem. Pointer is nicesly pass to main function but it seems that string information are lost...

    return 0;
}

char* read_data()
{

    char str1[100];
    char *p_str1;
    p_str1=(char*)malloc(100*sizeof(char));

gets(str1);
p_str1=str1;
    printf("entered string is: %s and pointer on that string is %p \n",p_str1,p_str1);
    //print from here is not a problem - works fine
    return p_str1;
}
  • The function `read_data` is returning a [dangling pointer](https://en.wikipedia.org/wiki/Dangling_pointer). – Andreas Wenzel Feb 13 '23 at 12:54
  • Side note: I suggest that you read this: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/12149471) – Andreas Wenzel Feb 13 '23 at 12:58
  • Why are you allocating two arrays of 100 bytes in the function `read_data`? You are allocating one array using `malloc` and one as an automatic object (i.e. a local variable). You only need one such array. Using the array allocated by `malloc` will work, but you are instead using the array declared as an automatic object. – Andreas Wenzel Feb 13 '23 at 13:01
  • Side note: It is generally recommended to call `free` when you no longer need the memory allocated by `malloc`. If you do not do this, then you have a [memory leak](https://en.wikipedia.org/wiki/Memory_leak). – Andreas Wenzel Feb 13 '23 at 13:04

0 Answers0