str = (char *) malloc(15);
If I do not type (char *)
, is there any difference in my program?
If I try to free the memory with free(str)
, linux freezes unexpectedly after running program.
str = (char *) malloc(15);
If I do not type (char *)
, is there any difference in my program?
If I try to free the memory with free(str)
, linux freezes unexpectedly after running program.
If you program in C, it does not make a difference, the preferred syntax is actually
char *str = malloc(15);
If you were programming in C++, the return value from malloc()
would not be cast implicitly as char *
for storing into str
. But in C++, you should not use malloc()
anyway, you should write str = new char[15];
and free this memory with delete []str;
.
A potential reason for free(str);
to cause undefined behavior is your writing to the array pointed to by str
beyond the first 15 bytes.
Use valgrind
to help track down where this happens.
char *malloc(size) unsigned size;
malloc() is used to allocate a certain number, size, of free memory and return a pointer to the beginning of it. The malloc() function is part of the dynamic allocation routines. If an allocation request fails- that is, if there is insufficient memory to fill the request- a null pointer is returned. You always must be very careful to make sure that you receive a valid pointer from malloc().
This is the general form of a program that will allocate 80 bytes of memory and then free them.
main()
{
char *p;
p= malloc(80);
if(!p){ printf("out of memory\n"); exit(2); }
.
.
.
free(p);
}