Troubleshooting
Fixing WinCC C Script Memory Growth From String Buffers
Short answer
Yes - writing a database field through a pointer aimed at a string literal is undefined behavior and a buffer overrun into 10 bytes of read-only storage, and it is not the leak. Days of script.exe growth come from database objects acquired per call and never released. Fix both: pass a caller-owned buffer with its capacity, copy at most bufferSize - 1 bytes, terminate explicitly, and release every acquired object on every exit path.
On this page
Yes, the pattern is a real fault - replace it - but it is two faults, not one. char *mystring = "something"; aims a pointer at 10 bytes of read-only storage, 9 characters plus the terminating null, so copying a database field through it is undefined behavior and a buffer overrun. That is not what grows script.exe over days. Gradual growth is unreleased database objects - recordsets, fields, connections - acquired on every call. Fix both: pass a caller-owned buffer with its capacity, copy at most bufferSize - 1 bytes and write the terminator yourself, and release every acquired object on every exit path.
The literal pointer is not a buffer #
char *mystring = "something"; initializes a pointer to a string literal. The storage behind a literal is sized for its own text alone, the compiler may place it in read-only memory, and the C standard makes any attempt to modify it undefined behavior. In practice the copy can fault on the spot, corrupt whatever follows the literal, or appear to work for months - "it has always run" proves nothing. Capacity fails even where the storage happens to be writable: space for one short literal can never hold a longer field.
The failing fragment names the copy strcopy in one place and strcpy in another. Whichever the project implements, if the copy runs to the source's null terminator and never takes a destination capacity, treat it as unbounded: one schema change, data import or unexpected value turns it into an overwrite.
Returning char* from the function is not the leak. The defects are the destination's storage class, its unknown capacity, and anything the query path allocates without releasing.
Pass a caller-owned buffer with its capacity #
At the call site:
/* Illustrative names */
char mystring[255];
f(mystring, sizeof(mystring));
At this call site sizeof(mystring) is the complete 255-byte array. Inside f the parameter is only a pointer, so applying sizeof there reports the pointer size rather than the caller's capacity - carry the explicit bufferSize argument down to the copy itself.
Open the function by validating and clearing:
void f(char *buffer, int bufferSize)
{
if (buffer == 0 || bufferSize <= 0)
return;
buffer[0] = '\0';
/* query and bounded transfer follow */
}
Writing buffer[0] = '\0' before any database work means every early return - null input, bad capacity, missing field, failed query - leaves an empty string instead of the previous cycle's text.
Copy at most bufferSize - 1 bytes #
A 255-byte array holds at most 254 bytes of field data plus the terminating null. Ask the database interface for the field's byte length - data bytes, terminator excluded - then clamp and terminate:
/* sourceLength is data bytes, terminator excluded */
int count = sourceLength;
if (count > bufferSize - 1)
count = bufferSize - 1;
memcpy(buffer, source, count);
buffer[count] = '\0';
memcpy never appends a terminator, so the final assignment is mandatory. memcpy_s is the cleaner primitive, but its availability in the WinCC 7.5 C-script environment is unconfirmed; do not make the repair depend on it. If the interface reports characters rather than bytes, or the field is multibyte-encoded, derive the byte count through that interface, because a character count is not a byte count.
The same field through both versions #
Take a field value of BATCH-2024-11-05-1430-A - 23 characters, so sourceLength is 23 and a terminator-to-terminator copy writes 24 bytes.
Old code: the literal behind "something" offers 9 + 1 = 10 bytes; 24 - 10 = 14 bytes land beyond it in storage the script does not own. Undefined behavior means any of silent corruption, a later crash, or apparent success.
New code: bufferSize is 255, the clamp limit is 255 - 1 = 254, and 23 stays under it, so count remains 23 - 23 bytes copied, the null at buffer[23], 24 of 255 bytes used, nothing outside the array.
Oversized field: the interface reports 262 data bytes. 262 > 254 clamps count to 254, the copy fills bytes 0 through 253, and buffer[254] holds the null - exactly the array, nothing past byte 254. Truncation keeps 254 of 262 bytes and drops 8, which is why identifiers and control values should be rejected rather than truncated: a truncated identifier is a different, valid-looking value. Decide the policy per field and keep it in one place.
The growth itself is unreleased objects #
No malloc and no free in the script does not mean nothing is allocated. The query path can create connections, command objects, recordsets, field values and error objects internally - the recordset behind rs->Fields("MyField") in the failing pattern is exactly such an object - and each one needs the matching close or release call the interface defines.
- List every database or query object acquired during one call.
- Move the releases onto a common exit path so query failure, a null field, an oversized value and a rejection all reach them.
- Clear local handles after release so a later pass cannot release the same object twice.
The two faults are independent. The overrun corrupts memory and crashes the station at unpredictable moments; the leak adds a similar amount on every call until script.exe runs out of memory days later. The isolation result you already have localizes it: with the script disabled the growth stops, so the fault sits on this script's path. Watch the right process while you test - script.exe carries the scripts of a WinCC PC runtime, whereas a Comfort panel that freezes is failing in its own runtime, a separate fault covered in Fixing HMIRTM.EXE Runtime Crashes on a Comfort Panel.
Prove the repair with equal call batches #
Run the batches on a development runtime or an idle station, never on a line that depends on the HMI - the paths you are exercising include the ones that crash it.
- Record the script.exe memory value before each batch.
- Run a fixed call count, for example 1000, with copying disabled but acquisition and release active.
- Run the same 1000 calls with the bounded copy enabled.
- Feed normal, empty, maximum-accepted, oversized and query-error values.
- Repeat each batch and compare the resting value once temporary work has drained.
Decision rule: equal batches must return to a stable band. A similar amount added after every batch is retention - something acquired per call and not released, so fix the release path first. Stable memory with wrong output points at length, termination or encoding handling. A crash at a boundary value points at an off-by-one clamp or a missed error return.
Checks before you call it fixed #
- Empty field value: the destination comes back empty,
buffer[0]is the null, no stale text. - Largest accepted value: exact match, with the terminator inside the array.
- Value beyond the limit: the documented reject-or-truncate path runs, and nothing is written past byte 254.
- Every forced query error: acquired and released object counts balance, and the destination stays empty.
- The proof of the bound: pre-fill the buffer with a known pattern, run the oversized case, then confirm the bytes after
buffer[254]are untouched.
Questions asked
Is returning a char pointer from the function the memory leak?
No. Returning a pointer copies nothing and holds nothing open. The gradual growth comes from database objects acquired on the query path and never released, while the literal destination is a correctness fault - undefined behavior and an overrun. Two different failures, and each needs its own fix.
Would a static char array inside the function be an acceptable quick fix?
It removes the read-only storage problem but creates a shared one: every caller writes into the same array, the second call overwrites the first caller's result, and two scripts running at the same time corrupt each other's strings with no error shown. The caller-owned buffer costs one line at each call site and has none of those failure modes.
Can I rely on memcpy_s in a WinCC 7.5 C script?
Not without confirming it exists in that scripting environment, because its availability there is unresolved. A count clamped to bufferSize - 1, one memcpy call and an explicit terminating null deliver the same protection with functions the environment already provides.
Our scripts have no malloc and no free, so where would a leak come from?
From the database interface. Query calls can allocate connections, commands, recordsets, field values and error objects internally, and each needs its matching close or release call. Count what each call acquires against what it releases; a mismatch on any exit path is your leak.
Why does the HMI freeze after days instead of failing at once?
Because each leaked object is small and each call adds roughly the same amount to script.exe. Nothing fails until the process can no longer allocate, and then a later call stops the station. The overrun, by contrast, corrupts or crashes unpredictably at any time, which is how you tell the two faults apart.