Hallo I have a question.
Is that valid, or have I then a memory lack?
Code:char *getArray(int n) { char *ptr = malloc(n); return ptr; } int main(void) { char *ptr = getArray(100); strcpy(ptr, "some stuff"); free(ptr); return 0; }
Hallo I have a question.
Is that valid, or have I then a memory lack?
Code:char *getArray(int n) { char *ptr = malloc(n); return ptr; } int main(void) { char *ptr = getArray(100); strcpy(ptr, "some stuff"); free(ptr); return 0; }
That would be valid yes. If you are unsure you can use valgrind to see if you are infact leaking memory. In this case, you are not.
And the reason you are valid is because the library function malloc is used to allocate a block of memory on the heap.
Thank you for quick answers.
To breimer273: I have to see how valgrind works.
To std10093: I had doubts, whether free() correct works if I allocate the memory in a separate block (in a function).
I figures that out,that's why i said that is been allocated into the heap.You successfully reserved a pointer (after the function terminated),so that you have access to what you allocated.That way you could access the heap and free the memory.If no pointer was reserved after the function was terminated,then you would be unable to free it,but the memory would remain allocated!