C语言, 帮忙看看哪里有bug

来源:百度知道 编辑:UC知道 时间:2024/05/09 03:38:41
我对c不熟悉,大家帮忙看看有哪些bug.

#include <types.h>
#include <kern/errno.h>
#include <kern/unistd.h>
#include <lib.h>

static char *my_kstrdup(const char *buf)
{
char *ptr, *ret;

ret = ptr = kmalloc(strlen(buf));
if(ptr = NULL)
panic("kmalloc returned NULL");

for(; *buf != '\0'; ++ptr, ++buf)
*ptr = *buf; /*这里应该是出错的地方*/

*ptr = '\0';

return ret;
}

static int my_toupper(int c)
{
if(c >= 'a' && c <= 'z')
return c - 'a' + 'A';

return c;
}

void complex_hello(void)
{
const char *msg = "hello World!!!";
char *copy;

/* my_kstrdup never returns a NULL pointer, no need to check */
copy = my_kstrdup(msg);

/* We want 'Hello Worl

个人觉得有两处bug
1:
if(ptr = NULL)//if(ptr == NULL) 估计是写错了
panic("kmalloc returned NULL");

2:
ret = ptr = kmalloc(strlen(buf)); //strlen 不会把buf最后的'\0'算上 而你最后又执行了*ptr = '\0'; 所以 改为ret = ptr = kmalloc(strlen(buf)+1);

for(; *buf != '\0'; ++ptr, ++buf)
*ptr = *buf; /*这里应该是出错的地方*/
直接ptr=buf就可以了
return ret;ret你有用到?

你说的应该出现问题的地方是正常的。
应该是你内存分配少了一个字节。strlen(buf)长度指的是字符串的实际字符数目,不包含'\0'字符串结束符。
执行完后,肯定内存乱掉了。

--对楼上的回答,坚决不同意;
ptr = buf是什么,那是指针值的赋值。此函数是用来字符串拷贝的。
*ptr = *buf 是说buf指针所指向的字符拷贝到ptr所指向的内存位置。
return ret 也是对的,这不是用到了吗,他是想把拷贝好的字符串起始内存位置返回。没什么错。

弱问一句这是在哪个环境下编的程序
不是Visual Studio吧

if(ptr = NULL)//这里应该用“==”
panic("kmalloc returned NULL");
char *copy;
copy = my_kstrdup(msg);//没有为copy分配内存

if(ptr = NULL)
panic("kmalloc returned NULL");
C语言的等号是==