0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h> 
#include <unistd.h>
#include <ctype.h>
#include <assert.h>


void *process(char **nbE) 
{
   char buffer[8] = "test";

   *nbE = &buffer[0];
   printf("%s\n", *nbE);
}

int main(int argc, char **argv) 
{
   char *str;
   process(&str);

   printf("%s\n", str);
}

I'm trying to get the value of *nbE in main() by making it points to the address of first char in my array. But it returns something not encoded, why?

What would be a way for me to do this way?

Note: I know I can do it simpler, I have a more complex code and this is a mini example

Basically I have something interesting in my array and want to pass it to my main function through a char* variable

yano
  • 4,827
  • 2
  • 23
  • 35
ADL92
  • 1
  • 3
  • `void *process` what exactly is this returning a pointer to? And you don't `return` anything anyway! – QuentinUK Nov 13 '22 at 00:08
  • your'e invoking [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior) by accessing the address of a local variable after it's gone out of scope. [This](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) is tagged c++ but it's the same concept – yano Nov 13 '22 at 00:19

1 Answers1

1
 char buffer[8] = "test";

creates a string that is local to the function, it is destroyed once you return from that function. Do this

 static char buffer[8] = "test";

or

  char * buffer = strdup("test");

you have to release the string when you have finsihed with it in the second case

pm100
  • 48,078
  • 23
  • 82
  • 145