char *getSubstring(char *string, int position, int length) { char *pointer; int c; pointer = malloc(length+1); if (pointer == NULL) { printf("Unable to allocate memory.\n"); exit(EXIT_FAILURE); } for (c = 0 ; c < position -1 ; c++) string++; for (c = 0 ; c < length ; c++) { *(pointer+c) = *string; string++; } *(pointer+c) = '\0'; return pointer; }
I was told that a memory leak occurs in this function because it dynamically allocates a substring buffer, but it is not released anywhere. Tell me how to fix a memory leak. I have to return the result, so you can’t call free(pointer)
before.
Wikipedia: Memory Leak .
UPD . More precisely, when this function is called, a memory leak occurs.
This function is called inside another function. Here is a piece of code:
char *func(int param) { /* Тут вычисляются значения Y, jm, len */ return getSubstring(Y, jm-len+1, len); }
The same question - how to fix? Here, too, you can not clear the memory! Is this a problem with my program structure?
i=0; while (other_dna != NULL) { /* ... */ myvar = func(/* ... */); /* используем myvar */ /* ... */ i++; }