看到《LINUX一站式编程》中有个习题,主要涉及堆空间和栈空间:
有两个结构体unit_t1和unit_t2,其中unit_t1申请了栈空间,不需要自己去考虑使用后释放空间的事情。unit_t2中申请了堆空间,需要自己释放。
定义部分如下
/* populator.h */
#ifndef POPULATOR_H
#define POPULATOR_H
typedef struct {
int number;
char msg[17];
}unit_t1;
typedef struct {
int number;
char* msg;
}unit_t2;
extern void set_unit_1(unit_t1 *p);
extern void set_unit_2(unit_t2 *p);
extern void delete_unit_2(unit_t2 *p);
#endif
实现部分如下
/* populator.cpp */
#include <string.h>
#include "populator.h"
void set_unit_1(unit_t1 *p)
{
if (p == NULL)
return;
p->number = 3;
strcpy(p->msg, "Hello World!");
}
void set_unit_2(unit_t2 *p)
{
if (p == NULL)
return;
p->number = 3;
p->msg= new char[17];
strcpy(p->msg, "Hello World!");
}
void delete_unit_2(unit_t2 *p)
{
delete []p->msg;
p->msg=

本文通过《LINUX一站式编程》中的习题探讨了C语言中结构体内的堆空间和栈空间使用。unit_t1利用栈空间,无需手动释放,而unit_t2使用堆空间,需要注意手动释放。在操作字符串时,如strcpy,必须留意目标空间类型,以避免内存管理错误。
最低0.47元/天 解锁文章
748

被折叠的 条评论
为什么被折叠?



