0

This is part of my code:

for(int i=0; i<10; i++)
{
    tab[i]=new char[80];
    oss.str("");
    oss<<"line number: <<i;
    temp=oss.str();
    tab[i]=(char*)temp.c_str();
}

and when I print the tab, the result is in turns 8 and 9. Am I doing something wrong?

Karol Borkowski
  • 532
  • 7
  • 19
  • 3
    Are you sure? As is this shouldn't even compile. Please post an [mcve] – NathanOliver Oct 22 '15 at 19:31
  • `(char*)temp.c_str()` bad idea! Modifying `tab[i][x]` now invokes undefined behavior. Also you're leaking the `new`ed array just 4 lines below its allocation… – Emil Laine Oct 22 '15 at 19:34
  • 1
    If by `tab[i]=(char*)temp.c_str();` you meant to copy the contents of `temp` to `tab[i]`, that doesn't do it; you're simply repointing the pointer. You need to use `strncpy`, or better yet, `std::string` in the first place. – Emil Laine Oct 22 '15 at 19:39
  • Temp is a string object. I used char arrays instead of strings, because it is just an excercise to practise arrays and pointers. How can I assign c-string to a char* in other way? – Karol Borkowski Oct 22 '15 at 19:50
  • 1
    You probably meant `strcpy(tab[i], temp.c_str());` . As you have it, `tab[i]` points at the internally managed string of `temp`, so later on when you reassign `temp` (next loop iteration), the previous `tab[i]` becomes a dangling pointer – M.M Oct 22 '15 at 19:58
  • You are right. The assumption by ostringstream is correct. The problem concerned thic casting. Thans! – Karol Borkowski Oct 22 '15 at 19:59

1 Answers1

2

Taking a bunch of comments and consolidating (Why are you commentators not answering instead?):

What you are actually doing there is changing the pointer value of tab[i] from your allocated memory to the internal string of temp. Which is a bad idea because temp will free that memory as soon as it is destructed.

You don't need temp at all, as far as I can see.

The C way to fix this is to use strcpy(tab[i], oss.str().c_str()) which will copy the characters one by one. Note that your current code does a new char[80] so if your string is longer than 79 characters it will overflow. If you must use a new'd buffer, do it with something like new char[oss.str().size() + 1]

The C++ way to fix this is to use an array of std::string instead of an array of char*. Then you could just assign, like tab[i] = oss.str() and it would copy it properly. It would also clean up the memory used when the array goes out of scope, as your code right now doesn't do.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131