What is the expected output for this char pointer function in Turbo C++?

In summary: Ok but it is correct I think in case of int pointer. Only char pointers have problem?Also after a scope ends, memory is reinitialized and since pointer points to memory its contents gets changed but in case of returning a char array the pointer is pointing to base address of array and since the array is in local scope, the whole memory gets reinitialized and hence contents of array gets changed. Is it right?Yes, that is correct. The pointer itself is returned correctly, but what it points to has been overwritten, so the contents of the pointer are invalid.
  • #1
Raghav Gupta
1,011
76

Homework Statement


This is the code on Turbo C++
Code:
char * disp()
{  
       int a [ ] = {49,15,50,34} ;
       char c [ ] ="1234" ;
       for (int i= 0; i<3 ; i++)
         c[i] =a[i] + c[i];
       cout<<c;
       return c;
}

void main()
{
      clrscr();
      cout<<" ,"<<disp()<<endl;
      getch();
}
What will be the output for this:
1. bAe4, undefined
2. bAe4, bAe4

Homework Equations

The Attempt at a Solution


I ran the program on turbo c++ and it was giving me the 1st option as output (undefined here I guess means random symbols like smilies which were appearing on my screen).
I thought it should be the 2nd one.
I know how we are getting bAe4 which is related to ASCII manipulation.
The thing is that when we are returning the c, it would be holding the same characters.
So, in the cout statement of main(), we should get bAe4 once again.
Why is that not true?
 
Last edited by a moderator:
Physics news on Phys.org
  • #2
Raghav Gupta said:

Homework Statement


This is the code on Turbo C++
Code:
char * disp()
{
       int a [ ] = {49,15,50,34} ;
       char c [ ] ="1234" ;
       for (int i= 0; i<3 ; i++)
         c[i] =a[i] + c[i];
       cout<<c;
       return c;
}

void main()
{
      clrscr();
      cout<<" ,"<<disp()<<endl;
      getch();
}
What will be the output for this:
1. bAe4, undefined
2. bAe4, bAe4

Homework Equations

The Attempt at a Solution


I ran the program on turbo c++ and it was giving me the 1st option as output (undefined here I guess means random symbols like smilies which were appearing on my screen).
I thought it should be the 2nd one.
I know how we are getting bAe4 which is related to ASCII manipulation.
The thing is that when we are returning the c, it would be holding the same characters.
So, in the cout statement of main(), we should get bAe4 once again.
Why is that not true?
The array named c is a local variable in your disp() function. The scope of c is only within disp(), so the call to cout within disp() works as expected, but c ceases to exist after the return from disp(). In Visual Studio, which I'm running, the compiler resets the memory that the c array was using after the return from disp(), so the call to cout in main() results in uninitialized garbage.
 
Last edited:
  • #3
Mark44 said:
The array named c is a local variable in your disp() function. The scope of c is only within disp(), so the call to cout within disp() works as expected, but c ceases to exist after the return from disp(). In Visual Studio, which I'm running, the compiler resets the memory that the c array was using after the return from disp(), so the call to cout in main() results in uninitialized garbage.

But why the output for this is 8 instead of garbage then, x also have scope to fact() only ?
C:
#include<iostream.h>
#include<conio.h>
int fact()
{
    int x=8;
    return x;
}

void main()
{
   clrscr();
   cout<<fact();
   getch();
}
 
  • #4
Perhaps because it is an integer value which is returned on the stack. The storage for x is reset, but the value is on the stack.
In your first example the returned value is a pointer to an array which no longer exists. You get a pointer on the stack, but where it points is no longer valid.
 
  • #5
Raghav Gupta said:
But why the output for this is 8 instead of garbage then, x also have scope to fact() only ?
C:
#include<iostream.h>
#include<conio.h>
int fact()
{
    int x=8;
    return x;
}

void main()
{
   clrscr();
   cout<<fact();
   getch();
}
In the earlier example of this thread, your disp() function returned an address, so the actual value returned was correct, but this was the address of a local variable, and the memory at that address was reinitialized just after the disp() function returned. This caused garbage to be displayed in main().
Merlin3189 said:
Perhaps because it is an integer value which is returned on the stack.
Since the value being returned is an int, it's more likely that it is being returned in a register, especially if the machine is one with an x86 architecture.
 
  • #6
Mark44 said:
In the earlier example of this thread, your disp() function returned an address, so the actual value returned was correct, but this was the address of a local variable, and the memory at that address was reinitialized just after the disp() function returned. This caused garbage to be displayed in main().
So the return is useful for int, double and other data types except char in this type of architecture?
Edit: It works for char also, also char* but not char[ ]
 
  • #7
Raghav Gupta said:
So the return is useful for int, double and other data types except char in this type of architecture?
Edit: It works for char also, also char* but not char[ ]
Right (including your edit comment). You can return a scalar (i.e, char, short, int, long, float, double, etc), but if you return a pointer, the contents of the memory at that location will be garbage if what is pointed to is of local scope.
 
  • #8
Mark44 said:
Right (including your edit comment). You can return a scalar (i.e, char, short, int, long, float, double, etc), but if you return a pointer, the contents of the memory at that location will be garbage if what is pointed to is of local scope.
Ok but it is correct I think in case of int pointer. Only char pointers have problem?
Also after a scope ends, memory is reinitialized and since pointer points to memory its contents gets changed but in case of returning a scalar what is happening?
Why scalar memory also not changes and therefore its value?
 
  • #9
Raghav Gupta said:
Ok but it is correct I think in case of int pointer. Only char pointers have problem?
No, it doesn't really have to do with the type of data that is pointed to, but it does seem to be that char arrays get reinitialized when they go out of scope, and other arrays don't have this happen (based on my installation of Visual Studio). Nevertheless, it's a bad idea to return a pointer to a local variable of a function. There's no guarantee that what's at that address won't have changed.
Raghav Gupta said:
Also after a scope ends, memory is reinitialized and since pointer points to memory its contents gets changed but in case of returning a scalar what is happening?
Why scalar memory also not changes and therefore its value?
Whatever you return gets copied somewhere, likely to one of the CPU registers. If you return a pointer to some type, that address gets copied with no problem, but what's at the address may or may not be valid if the thing pointed to is a local variable that's now out of scope.
 
  • Like
Likes Raghav Gupta
  • #10
So if this statement char c [ ] ="1234" ; were moved into main() then the program should execute as hoped?
 
  • #11
NascentOxygen said:
So if this statement char c [ ] ="1234" ; were moved into main() then the program should execute as hoped?
No.
Here's the change you described:
C:
char * disp()
{
       int a [ ] = {49,15,50,34} ;
     
       for (int i= 0; i<3 ; i++)
         c[i] =a[i] + c[i];
       cout<<c;
       return c;
}

void main()
{
      clrscr();
      char c [ ] ="1234" ;
       cout<<" ,"<<disp()<<endl;
      getch();
}
The code above won't compile, as the identifier c isn't known to or accessible by the disp() function. Here the scope of the identifier c is just main().

You could get around this by declaring c outside of all functions, making it a global variable, like so:

C:
char * disp();   // Declaration of disp() function
char c [ ] ="1234" ;  // Array c is now global, accessible by both main() and disp()

int main()
{
    cout<<" ,"<<disp()<<endl;
    return 0;
}

char * disp()
{
   int a [ ] = {49,15,50,34} ;
      
   for (int i= 0; i<3 ; i++)
         c[i] =a[i] + c[i];
   cout<<c;
   return c;
}

Note that I have modified the original code somewhat, by moving main() to the top (my preference), and removing some nonessential lines of code. Also, this isn't complete code, as it doesn't either include the necessary header files or have the proper using statement.
This workaround is not an ideal solution, as global variables are discouraged, for the most part.

Here is a better solution, and one that is a complete, working program.
C:
using std::cout;
using std::endl;

char * disp(char *);   // Declaration of disp() function
 
int main()
{
    char c [ ] ="1234" ;
    cout << " ," << disp() << endl;
    return 0;
}

char * disp(char * c)
{
   char a [ ] = {49, 15, 50, 34} ;
      
   for (int i = 0; i < 3 ; i++)   // Note that only c[0], c[1], and c[2] are modified
         c[i] = a[i] + c[i];
   cout << c;
   return c;
}

Output is bAe4 , bAe4, same as 2nd answer in the original post.
 
  • Like
Likes NascentOxygen
  • #12
Mark44 said:
Nevertheless, it's a bad idea to return a pointer to a local variable of a function. There's no guarantee that what's at that address won't have changed.
In linked list we usually do that -returning head node.
Eg:
Linkedlist * Linkedlist::del (int val, Linkedlist* head){
...
...
return head;}
Here head does not get reinitialized.
Is it only the problem with char arrays?
 
  • #13
Raghav Gupta said:
In linked list we usually do that -returning head node.
Eg:
Linkedlist * Linkedlist::del (int val, Linkedlist* head){
...
...
return head;}
Here head does not get reinitialized.
Is it only the problem with char arrays?
Mark44 said:
but it does seem to be that char arrays get reinitialized when they go out of scope, and other arrays don't have this happen (based on my installation of Visual Studio).
 
  • #14
So, it depends on the type of software which you have and compilers? As apart from visual studio this also happens on turbo c++
 
  • #15
Raghav Gupta said:
So, it depends on the type of software which you have and compilers? As apart from visual studio this also happens on turbo c++
It is probably implementation-dependent. As far as I know, there is nothing in how the language is defined that causes this to happen.
 
  • #16
Mark44 said:
It is probably implementation-dependent. As far as I know, there is nothing in how the language is defined that causes this to happen.
So in general, we should not return pointers by the definition of language. It was only chance or implementation dependent that I was getting correct value for integer arrays?
 
  • #17
Raghav Gupta said:
So in general, we should not return pointers by the definition of language.
It has nothing to do with how the language is defined. If a variable is defined inside a function, it is local to that function. The function should not return a pointer to that variable, because there's no guarantee that the memory being pointed to won't get re-used for some other purpose (hence, have its value changed).
Raghav Gupta said:
It was only chance or implementation dependent that I was getting correct value for integer arrays?
That's what I think.
 
  • Like
Likes Raghav Gupta
  • #18
Thanks for solving queries.
 

Related to What is the expected output for this char pointer function in Turbo C++?

What is a char pointer function output?

A char pointer function output is a value that is returned from a function that has a char pointer as its return type. This value can be a single character or a string of characters.

How do I declare a char pointer function?

To declare a char pointer function, you must use the syntax: char* functionName(parameters); The asterisk (*) indicates that the function will return a char pointer.

How do I use the output of a char pointer function?

To use the output of a char pointer function, you can assign it to a variable of type char pointer or print it using a print statement. You can also use it in other functions that require a char pointer as an argument.

What happens if a char pointer function does not have a return statement?

If a char pointer function does not have a return statement, the function will still run but it will not have an output. This can result in unexpected behavior in your program, so it is important to always have a return statement in your functions.

How do I free the memory allocated for a char pointer function output?

To free the memory allocated for a char pointer function output, you can use the free() function. This function takes in a pointer as an argument and deallocates the memory associated with it, preventing any memory leaks in your program.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
968
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
17
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
14
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
909
  • Engineering and Comp Sci Homework Help
Replies
3
Views
684
  • Engineering and Comp Sci Homework Help
Replies
8
Views
2K
Back
Top