BendixDeveloper
BendixDeveloper

Reputation: 123

Returning an array allocated with malloc and not using the return

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!

Upvotes: 1

Views: 53

Answers (1)

Arnaud Peralta
Arnaud Peralta

Reputation: 1305

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.

Upvotes: 1

Related Questions