Freeing memory

This is a discussion on Freeing memory within the C Programming forums, part of the General Programming Boards category; Hi,
Below is a code that has been written so that I can compute the fibinacci sequence using threads based ...

Freeing memory

Hi,
Below is a code that has been written so that I can compute the fibinacci sequence using threads based on user input at command line. The program has been written for a linux OS.
There is a statement close to the exit of the program where I am trying to free the memory that I allocated to store the fibonacci sequence. Every time I try to free the memory using the free() system call, it gives me a "glibc detected" error AFTER printing the correct output. If I comment out the line where I am freeing the memory, there are no issues. Can anyone suggest, what I might be doing wrong?
Thanks
V

From the way your code looks, you seem to expect myPtr to be used as an int array. Which means, they way you allocated the memory for myPtr

Code:

myPtr = (int*) malloc(intValue + 2);

is wrong because what you basically are doing is allocating intValue+2 bytes of memory. Based on that this code

Code:

for(j = 0; j <= integerParam; j++)
myPtr[j] = sequence[j];

is a buffer overflow. The usual way to allocate array is by using the calloc() function (do man calloc to find out more). Granted that many C/C++ reference materials do that to allocate memory for C-style strings, it doesn't mean it's necessarily the best way to do things.

Second, the code below moves myPtr to a memory location that you didn't allocate:

Code:

for(i = 0; i <= intValue; i++){
printf("%d ", *myPtr);
myPtr++;

.
By the time the for loop is done, myPtr is now pointing to something else.

C and C++ users who are well-versed in pointer arithmetic and the nuances of memory allocation can get away with code like what you did above. However, I suggest that you stay away from it for the sake of others who will sooner or later have to read your code. However, if you're really interested in how this code could be corrected let me know and I'll send it to you as a private message.

[Quote]
C and C++ users who are well-versed in pointer arithmetic and the nuances of memory allocation can get away with code like what you did above. However, I suggest that you stay away from it for the sake of others who will sooner or later have to read your code. However, if you're really interested in how this code could be corrected let me know and I'll send it to you as a private message. [\Quote]

Thank you for the detailed reply. It helped a lot. I would like to learn the right way of doing this. I would appreciate your help in letting me know what the correct code would look like. Let me know what I should correct. Thanks vbdave78@yahoo.com