problem with malloc/free

Started by
4 comments, last by laotzu 22 years, 6 months ago
I''m having a problem when I try to use free, I keep getting a bus error. Here''s the code, char fname[28]; char *czFileName; ... czFileName = (char*)malloc(sizeof(char*)*sizeof(fname)); strcpy(czFileName, fname); ... if(czFileName != NULL) free(czFileName); The bus error comes in when I try to free czFileName. Any help would be appreciated. Thank you, -lao
Advertisement
The problem is that the allocated string is only 1 byte long. sizfo(string) DOES NOT give the length of the string but the size of the pointer (4).

Try this instead :

czFileName = (char*)malloc(strlen(fname)+1);


quote:Original post by Prosper/LOADED
The problem is that the allocated string is only 1 byte long. sizfo(string) DOES NOT give the length of the string but the size of the pointer (4).

Try this instead :

czFileName = (char*)malloc(strlen(fname)+1);




Well, more properly,

czFileName = (char*)malloc(sizeof(*fname)*(strlen(fname)+1));

Then you'll be a bit more ready for localization.

Edited by - cheesegrater on October 19, 2001 3:20:49 PM
Ahh.. ok, great!

thanks for the explanation

-lao
Ahh.. ok, great!

thanks for the explanation

-lao
quote:Original post by Prosper/LOADED
The problem is that the allocated string is only 1 byte long. sizfo(string) DOES NOT give the length of the string but the size of the pointer (4).


A good theory. Unfortunately its wrong.

  char blargh[ 100 ];cout << sizeof( blargh )  


This _will_ display 100. What you are saying is only true for dynamically allocated arrays. The compiler knows the size of blargh at compile time, and will be able to insert the proper value. If blargh had been a char* instead of a char[], your statement would have been true.
A sizeof is little more than a preprosessor macro, evaluating to the size of the supplied data type at compile time. It incurs no runtime performance penalty.
The only think I can see thats wrong with his code is that he is doing sizeof( char* ). It should be sizeof( char ), or he could omit it alltogether since the size of a char is known. However, this doesnt solve his problem.

(Whats a bus error anyway?)





"A society without religion is like a crazed psychopath without a loaded .45"
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]

This topic is closed to new replies.

Advertisement