鱼C论坛

 找回密码
 立即注册
查看: 2472|回复: 3

这个内存释放如何加?

[复制链接]
发表于 2012-1-27 05:53:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <stdio.h>
#include<stdlib.h>
#include<string.h>

const size_t BUFFER_LEN = 512;              /* Size of input buffer      */
int main(void)
{
  char buffer[BUFFER_LEN];                  /* Store for strings         */
  char *pS[3] = { NULL };                   /* Array of string pointers  */
  char *pbuffer = buffer;                   /* Pointer to buffer         */
   size_t index = 0;
  int i=0;/* Available buffer position */
  printf("\nEnter 3 messages that total less than %u characters.", BUFFER_LEN-2);
  /* Read the strings from the keyboard */
  for(int i=0 ; i<3 ; i++)
  {
    printf("\nEnter %s message\n", i>0 ? "another" : "a" );
pS[i]=(char*)malloc(strlen(buffer));
    pS[i] = &buffer[index];/* Save start of string      */

    /* Read up to the end of buffer if necessary */
    for( ; index<BUFFER_LEN ; index++)      /* If you read \n ... */
      if((*(pbuffer+index) = getchar()) == '\n')
        {
          *(pbuffer+index++) = '\0';
    /* ...substitute \0   */
          break;
        }
    /* Check for buffer capacity exceeded */
    if((index == BUFFER_LEN) && ((*(pbuffer+index-1) != '\0') || (i<2)))
    {
      printf("\nYou ran out of space in the buffer.");
      return 1;
    }
  }
  printf("\nThe strings you entered are:\n\n");
  for(int i = 0 ; i<3 ; i++)
  {
    printf("%s\n", pS[i]);
  }
  free(pS[i]);
  pS[i]=NULL;我在这里使用释放,为什么发生内存错误!我该怎么改.
  printf("The buffer has %d characters unused.\n",
                     BUFFER_LEN-index);

  
  return 0;
}




                               
登录/注册后可看大图
该贴已经同步到 空手套小白狼的微博
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-1-27 13:56:47 | 显示全部楼层
你这个错的太恼火了。。。
小甲鱼最新课程 -> https://ilovefishc.com
 楼主| 发表于 2012-1-27 20:01:10 | 显示全部楼层
cuibaowenown2 发表于 2012-1-27 13:56
你这个错的太恼火了。。。

我的意思释放内存在哪里加?
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-1-27 20:22:18 | 显示全部楼层
空手套小白狼 发表于 2012-1-27 20:01
我的意思释放内存在哪里加?

注意看你的定义是:char *pS[3];
所以定义了三个指针,即:pS[0],pS[1],pS[2]
所以应该:free(pS[0],pS[1],pS[2])
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-11 00:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表