• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# problem with malloc/free

## Recommended Posts

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

##### Share on other sites
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).

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

##### Share on other sites
quote:
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).

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

##### Share on other sites
Ahh.. ok, great!

thanks for the explanation

-lao

##### Share on other sites
Ahh.. ok, great!

thanks for the explanation

-lao

##### Share on other sites
quote:
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"

• ### Forum Statistics

• Total Topics
627711
• Total Posts
2978763

• 21
• 14
• 12
• 41