Skip to contentSkip to conversation

malloc and free

DISCUSSION Sameer Maggon 3 participants 3 messages May 20, 2002

lore
Share & tools
lore
#0 lore raw

Hi,
In one function i have a definiton like

  char *token;
  token = (char *)malloc(256 * sizeof(char));

  ...
  ...
  token = strtok(...,"\0");
 
  ...
  free(token);

Now the problem is that sometimes this runs
fine and sometimes it crashes on free()..
Why so.
If I remove the free(..), then the program
works perfectly fine

How do i correct the problem.

Regards
Sameer

--------------
http://www.dypatil.edu For Better tomorrow

#1 lore raw

Hi Sameer,

On Mon, 20 May 2002 16:56:30 +0530 (IST) Sameer Maggon <[email protected]> wrote:

[snip]

Quoted 6 lines
  char *token;
  token = (char *)malloc(256 * sizeof(char));

  ...
  ...
  token = strtok(...,"\0");

[snip]

The problem is there, you change "token"'s value, so you lost the value formerly returned by malloc (this one has to be free()'ed) because strtok returns a pointer to the next token IIRC. Then, the "token" you attempt to free is not the good one.

For instance, if I didn't miss anything:

	char *token, *buffer;
	buffer = (char *)malloc(256 * sizeof(char));
	token = buffer;
	token = strtok(...,"\0");
	..
	free(buffer);

Regards,

Signature · 1 line
wwp
#2 lore raw
In reply to Sameer Maggon
Quoted 5 lines · Sameer Maggon

Hi,
In one function i have a definiton like

  char *token;
  token = (char *)malloc(256 * sizeof(char));

No real need to cast here and in fact it could mask a missing #include <stdlib.h>.

man malloc
---< snip
RETURN VALUES
For calloc() and malloc(), the value returned is a pointer to the allocated memory, which is suitably aligned for any kind of variable, or NULL if the request fails.
---> snip

Also, char is always size 1 so there is no need for the sizeof(). If you did want to use sizeof() use it with the object not the type so that if you want to change the type of the object you don't need to also change the malloc:

token = malloc(256 * sizeof(*token));

Also, I assume you are checking the return value of the malloc is not NULL at some point.

if ( ( token = malloc(256) ) == NULL )

{
	puts("Malloc: Memory allocation failed.");
	exit(1);
}
Quoted 4 lines
  ...
  ...
  token = strtok(...,"\0");

Here's the problem, you are assigning another value to token and have lost track of your malloc'd memory.

Quoted 3 lines
  ...
  free(token);

Free may now be freeing the wrong memory.

Signature · 5 lines
Andrew Edmondson
Test Development Engineer
<-------------------------->
The discerning heart seeks knowledge, 
but the mouth of a fool feeds on folly.