0

With a called function MyFn that allocates memory:

Error MyFn(_Outptr_result_maybenull_ OBJ** const objs,
           _Out_ unsigned int* const numObjs) {
    ...
}

int main(void) {
    OBJ* objs = NULL;
    unsigned int numObjs = 0;
    MyFn(&objs, &numObjs);
    if (objs != NULL) {
        for (int i = 0; i < numObjs; i++) {
            OBJ* obj = objs[i]; // Reading invalid data from objs.
        }
    } 
}

Is it possible to annotate numObjs as the number of OBJ* written to objs so that SAL doesn't warn me that I'm potentially reading invalid data while iterating?

wulfgarpro
  • 6,666
  • 12
  • 69
  • 110
  • You code simply wrong, how minimum in 3 places. – RbMm Jan 24 '23 at 05:26
  • The code doesn't compile. Can you show your *actual* code? – IInspectable Jan 24 '23 at 06:29
  • Change `MyFn(&objs, numObjs);` to `MyFn(&objs, &numObjs);` and also `OBJ* obj = *(OBJ*)(objs[i])` to `OBJ* obj = objs[i]`. As for SAL annotation, I don't know, maybe something like `_Out_writes_to_(s,c)` might help you? – Remy Lebeau Jan 24 '23 at 17:45
  • @RemyLebeau but objs declared as `OBJ*` and not as `OBJ**` so expression `obj =objs[i]` anyway wrong. Need or `obj = objs + i` or declare `OBJ** objs` and fn with `OBJ***` argument. Unclear - fn must return. Array of `OBJ` or array of pointers `OBJ*` – RbMm Jan 24 '23 at 18:52
  • 1
    @RbMm Sorry, I meant `OBJ* obj = &objs[i]` or `OBJ& obj = objs[i]` – Remy Lebeau Jan 24 '23 at 19:48
  • 1
    If `MyFn` returns an array of `OBJ*`'s you can use `_Outptr_result_buffer_(*numObjs)` as the annotation (see [Output pointer parameters](https://learn.microsoft.com/en-us/cpp/code-quality/annotating-function-parameters-and-return-values?view=msvc-170#output-pointer-parameters) for a full list). – IInspectable Jan 24 '23 at 21:16
  • 1
    Regardless, the code still doesn't compile as posted. Please show a [mcve]. If you don't want to share the implementation of `MyFn`, just mark it `extern`. Since we only need to be able to reproduce the compilation phase, a subsequent linker failure isn't harmful. – IInspectable Jan 26 '23 at 10:37

0 Answers0