Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Without knowing what the error is, it's hard to say, but this line:</p> <pre><code>const char* cstr[80]; </code></pre> <p>seems wrong: it creates an array of 80 pointers; when it implicitly converts to a pointer, the type will be <code>char const**</code>, which should give an error when it is passed as an argument to <code>strcpy</code>, and the dereference in the return statement is the same as if you wrote <code>cstr[0]</code>, and returns the first pointer in the array&mdash;since the contents of the array have never been initialized, this is undefined behavior. </p> <p>Before you go any further, you have to define what the function should return&mdash;not only its type, but where the pointed to memory will reside. There are three possible solutions to this:</p> <dl> <dt>Use a local static for the buffer:</dt> <dd> This solution was frequently used in early C, and is still present in a number of functions in the C library. It has two major defects: 1) successive calls will overwrite the results, so the client code must make its own copy before calling the function again, and 2) it isn't thread safe. (The second issue can be avoided by using thread local storage.) In cases like yours, it also has the problem that the buffer must be big enough for the data, which probably requires dynamic allocation, which adds to the complexity. </dd> <dt>Return a pointer to dynamically allocated memory:</dt> <dd> This works well in theory, but requires the client code to free the memory. This must be rigorously documented, and is extremely error prone. </dd> <dt>Require the client code to provide the buffer:</dt> <dd> This is probably the best solution in modern code, but it does mean that you need extra parameters for the address and the length of the buffer. </dd> </dl> <p>In addition to this: there's no need to use <code>std::ostringstream</code> if all you're doing is concatenating; just add the two strings. Whatever solution you use, verify that the results will fit.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload