UNIX环境高级编程学习之第七章进程环境-存储器分配malloc
[code lang="cpp"]#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
char* newChar(int size)
{
return (char*)malloc(size);
}
int newInt(int** ppInt, long size)
{
*ppInt = (int*)malloc(size);
if (*ppInt == NULL)
{
printf("malloc Error/n");
exit(-1);
}
return 0;
}
int main(int argc, char* argv[])
{
printf("pid=%lu/n", getpid()); // 进程ID
char* pChar = NULL;
pChar = newChar(512);
if (NULL == pChar)
{
printf("malloc Error/n");
exit(-1);
}
memset(pChar, '/0', 512);
strcpy(pChar, "WanZhenjie");
printf("pChar=%s/n", pChar);
int* pInt;
newInt(&pInt, 512);
int i;
for (i=0;i<10;i++)
{
pInt[i] = i;
}
for (i=0;i<10;i++)
{
printf("pInt[%d]=%d/n", i, pInt[i]);
}
// 释放空间
free(pChar);
free(pInt);
pChar = NULL;
pInt = NULL;
return 0;
}
[/code]
文章评论