1

I am writing a function which returns an array. In this function I want to do some calculations to give me an integer, which is the size of the array I want to allocate memory to. In the function I therefore use malloc to allocate an array with the specific size and I return this array called returnArray.

However, what happens if I call the function without using the return? Will the allocated memory still be allocated? Is this a very bad problem? I suspect memory leak, but I'm not entirely sure.

char * findValueAndCreateArray() {
int value = 0;

while(something, something..) {
value++;
}

char * returnArray = (char*) malloc(sizeof(char) * value);

return returnArray;

}

findValueAndCreateArray;

Thanks in advance!

2
  • You should show your code to make the question more clear. If your function returns the address of the allocated memory and you don't use and later free it, you will create a memory leak. This is not much different from calling malloc(some_size) and ignoring its return value. Commented Feb 18, 2019 at 17:39
  • @Bodo I now added the code. Thanks for the answer. Commented Feb 18, 2019 at 18:13

1 Answer 1

1

Yes, it will do a memory leak. When you return something from a function in C, you just copy a value. So when you are doing a malloc(), you catch the adress of your allocated memory but this space will be allocated until the end of your program or a free(returnArray);

And also, you should use a size_t variable when you are allocating space with malloc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.