以下代码有问题吗?如果有,是什么问题,怎么改正。 void getmemory( char *p ) { p = (char *) malloc( 100 ); } void test( void ) { char *str = null; getmemory( str ); strcpy( str, "hello world" ); puts( str ); }
时间: 2023-06-10 09:04:17 浏览: 123
有问题。在getmemory函数中,为指针分配了内存空间,但是分配的空间地址并没有传递出去,因此在调用test函数时,str指针是未初始化的,并不指向任何内存空间。修改方法是,在getmemory函数中改为传递指针的地址,并在test函数中对指针进行解引用,如下所示:
void getmemory( char **p ) {
*p = (char *) malloc( 100 );
}
void test( void ) {
char *str = NULL;
getmemory( &str );
strcpy( str, "hello world" );
puts( str );
}
相关问题
以下程序,会存在什么问题?如果有问题,请更正. void GetMemory(char *p) { p = (char *)malloc(100); } void Test(char *s) { char *str = NULL; GetMemory(str); strcpy(str, s); printf(str); }
以上程序存在问题,因为在GetMemory函数中分配的内存地址被赋值给了GetMemory函数中的局部变量p,而不是Test函数中的指针str。因此,在Test函数中使用str指针时,它指向的仍然是NULL,从而导致程序运行时出现段错误。
为了解决以上问题,可以将GetMemory函数修改为传入指针的地址,即将char *p改为char **p。这样,在GetMemory函数中分配的内存地址就可以通过指针的指针修改Test函数中的指针str所指向的地址。
修改后的代码如下:
```c++
void GetMemory(char **p) {
*p = (char *)malloc(100);
}
void Test(char *s) {
char *str = NULL;
GetMemory(&str);
strcpy(str, s);
printf("%s", str);
}
```
这样就可以正确地分配内存并使用指针str了。
纠错 void GetMemory( char **p, int num ) { *p = (char *)malloc(num); } void Test( void ) { char *str = NULL; GetMemory(&str, 100); strcpy(str, "hello"); printf(str); }
纠错后的代码如下:
```
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf("%s", str);
free(str); // 记得释放内存
}
```
需要注意以下几点:
1. 在 `printf` 语句中,需要使用 `%s` 格式化字符串的输出。
2. 在使用 `malloc` 分配内存后,需要在合适的时机手动释放内存,否则会出现内存泄漏的问题。这里我们在程序结尾处使用了 `free` 函数释放了内存。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)