Reputation: 519
I have trouble deallocating memory that I allocated using malloc. The program runs fine until it the part where it's supposed to deallocate memory using free. Here the program freezes. So I was wondering what the problem could be since I'm just learning C. Syntactically the code seems correct so could it be that I need to delete all the stuff in that location before deallocating memory from that location or something else?
Here's the code.
// Program to accept and print out five strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NOOFSTRINGS 5
#define BUFFSIZE 255
int main()
{
char buffer[BUFFSIZE];//buffer to temporarily store strings input by user
char *arrayOfStrngs[NOOFSTRINGS];
int i;
for(i=0; i<NOOFSTRINGS; i++)
{
printf("Enter string %d:\n",(i+1));
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer)+1));//calculates string length and allocates appropriate memory
if( arrayOfStrngs[i] != NULL)//checking if memory allocation was successful
{
strcpy(arrayOfStrngs[i], buffer);//copies input string srom buffer to a storage loacation
}
else//prints error message and exits
{
printf("Debug: Dynamic memory allocation failed");
exit (EXIT_FAILURE);
}
}
printf("\nHere are the strings you typed in:\n");
//outputting all the strings input by the user
for(i=0; i<NOOFSTRINGS; i++)
{
puts(arrayOfStrngs[i]);
printf("\n");
}
//Freeing up allocated memory
for(i=0; i<NOOFSTRINGS; i++)
{
free(arrayOfStrngs[i]);
if(arrayOfStrngs[i] != NULL)
{
printf("Debug: Memory deallocation failed");
exit(EXIT_FAILURE);
}
}
return 0;
}
Upvotes: 1
Views: 8291
Reputation: 24919
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer)+1));//calculates string length and allocates appropriate memory
Shouldn't that be
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer))+1);
Upvotes: 2
Reputation: 170549
You misuse strlen()
and this results in buffer overrun:
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer)+1)); //pointer from gets() is incremented and passed to strlen() - that's wrong
should be
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer))+1); //pointer from gets() is passed to strlen(), then returned value is incremented - correct
also free()
doesn't change the pointer passed to it. So that
char* originalValue = pointerToFree;
free( pointerToFree );
assert( pointerToFree == originalValue ); //condition will always hold true
and so in your code freeing memory should just be
//Freeing up allocated memory
for(i=0; i<NOOFSTRINGS; i++)
{
free(arrayOfStrngs[i]);
}
Upvotes: 4