#include
#include
#define MAX 30
void push(char );
char stack[MAX];
int tos=0;
int main(){
char str[]=\"Arijit Saha\";
char *f
In this code:
char* rev(char s[]) {
char reverse[strlen(s)];
...
return reverse;
}
reverse
is an temporary array with automatic storage duration that is being deallocated once the execution leaves the scope of this function. You return a pointer that becomes a dangling pointer.
Trying access the memory that this pointer points to produces undefined behavior.
Apart from the fact that you should allocate it dynamically by using malloc
, note that strlen
returns the length of the string, you will also need the space for the terminating character ('\0'
). You should create reverse
like this:
char* reverse = malloc(strlen(s) + 1);
and don't forget to assign '\0'
to the last character of reverse
. Also don't forget that the caller of this function becomes responsible for deallocating the memory that has been allocated by malloc
, i.e. the caller should call free
on the returned pointer.