Why does this function allocating memory in a function not work correctly?

This code does not give me the expected data in mystr, I get "Unhandled exception at 0x012D2CE3 in Project1.exe: 0xC0000005: Access violation reading location 0x00000000." instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>;

using namespace std;

void myfunc(char* str)
{
	str = new char[3];
	str[0] = 'a';
	str[1] = 'B';
	str[2] = 0;
}

int main(void)
{
	char* mystr = nullptr;
	myfunc(mystr);
	cout << mystr[0] << std::endl;
	cout << mystr[1] << std::endl;
	system("PAUSE");
	return 0;
}


What is wrong with this code? What is the correct way to write this in C? What is the correct way to write this in C++?
Last edited on
I do not think that is good idea to change an address of the variable inside the procedure but it is possible:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void myfunc(char *&str)
{
  str = (char*)malloc(3);
  str[0] = 'a';
  str[1] = 'B';
  str[2] = 0;
}
void	main()
{
  char *mystr;
  myfunc(mystr);
  cout << mystr[0] << std::endl;
  cout << mystr[1] << std::endl;
  free(mystr);
}

Last edited on
"Correct"? Debatable. Here is one:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

int main(void)
{
  std::string mystr;

  // the '=' is actually a  function that probably
  // invokes dynamic allocation
  mystr = "aB";

  // print each character, no more, no less
  for ( char x : mystr ) {
    std::cout << x << '\n';
  }

  return 0;
  // the destructor of mystr takes care of deallocation
}
Topic archived. No new replies allowed.