malloc
malloc(0)可能会返回一个非NULL的指针,但是不能对这个指针做写的操作,也不能free,虽然free不会出错。
malloc(-1),负数时,会返回NULL指针。
下面的写法也许更好一些。
void *my_malloc(size_t __size)
{
if (__size <= 0)
{
return 0;
}
return malloc(__size);
}
realloc
If the function fails to allocate the requested block of memory, a null pointer is returned, and the memory block pointed to by argument ptr is not deallocated (it is still valid, and with its contents unchanged).
当realloc出错时,可能会造成内存泄露,看下面的代码注释。
int main()
{
//错误的写法,当realloc失败时,p1会变为空,但是开始malloc的10个字节内存还在,所以会导致内存泄露
void *p1 = malloc(10);
p1 = realloc(p1, 1000);
if (p1)
{
free(p1);
p1 = 0;
}
//正确的写法,只有当p3分配成功时,才更新之前的内存p2
void *p2 = malloc(10);
void *p3 = realloc(p2, 1000);
if (p3)
{
p2 = p3;
}
if (p2)
{
free(p2);
p2 = 0;
}
return 0;
}
readlink
int readlink (const char *filename, char *buffer, size t size) [Function]
The readlink function gets the value of the symbolic link filename. The file name that the link points to is copied into buffer. This file name string is not null-terminated;
readlink normally returns the number of characters copied. The size argument
specifies the maximum number of characters to copy, usually the allocation size of buffer.
readlink()会将参数path 的符号连接内容存到参数buf 所指的内存空间, 返回的内容不是以NULL作字符串结尾, 但会将字符串的字符数返回. 若参数bufsiz 小于符号连接的内容长度, 过长的内容会被截断.
If the return value equals size, you cannot tell whether or not there was room to
return the entire name. So make a bigger buffer and call readlink again.
如果返回的字符数等于参数size,你不能判断出实际的字符数正好是size还是比size大,所以将buffer增大一些,重新调用readlink。
下面这个写法是OK的。
char *readlink_malloc(const char *filename)
{
int size = 100;
char *buffer = NULL;
while (1)
{
buffer = (char *)realloc(buffer, size);
int nchars = readlink(filename, buffer, size);
if (nchars < 0)
{
free(buffer);
return NULL;
}
if (nchars < size)
return buffer;
size *= 2;
}
}
网友评论