练习中的动态内存分配

时间:2014-10-11 00:00:03

标签: c memory-management

程序从标准输入中读取行。每行都打印在标准输出上,前面是行号。该程序没有内置限制它可以处理的行数。

我的回答是:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 30

int main(){  

int line_n=0;
char line[MAXSIZE];
char *p;

while(gets(&line))
{ 
  if('\n'){
    if(*line=='q') break;
    else if(strlen(line)>MAXSIZE){
    p=&line;
    p=(char *)malloc(sizeof(strlen(line))); //failed to use dynamic memory allocation here
        printf("%d).",line_n);
        printf("%s\n",line);
      }
   else{
  printf("%d).",line_n);
  printf("%s\n",line);
    }
 }
  line_n++;
}

我是C编程的新手,我需要有关动态内存分配的帮助。当我的输入大于MAXSIZE时,我有溢出。

2 个答案:

答案 0 :(得分:1)

试试这个:

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

#define ALLOCSIZE 30

int main()
{  
    int line_n = 0;
    char *line = NULL;
    int linelen = 0;
    int linecap = 0;
    char *p;
    int c;

    while ((c = fgetc(stdin)) != EOF)
    {
        if (c == '\n')
        {
            if ((line) && (*line == 'q'))
            {
                linelen = 0;
                break;
            }

            printf("%d).%.*s\n", line_n, linelen, line);
            linelen = 0;
            line_n++;
        }
        else
        {
            if (linelen == linecap)
            {
                p = (char *) realloc(line, linecap + ALLOCSIZE);
                if (!p) break;
                line = p;
                linecap += ALLOCSIZE;
            }

            line[linelen] = c;
            linelen++;
        }
    }

    if (linelen > 0)
        printf("%d).%.*s\n", line_n, linelen, line);

    free(line);

或者这个:

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

int main()
{  
    int line_n = 0;
    char *line = NULL;
    size_t linelen = 0;
    char *p;

    while (getline(&line, &linelen, stdin) != -1)
    { 
        if (*line == 'q') break;
        printf("%d).%.*s\n", line_n, linelen, line);
        line_n++;
    }

    free(line);

答案 1 :(得分:0)

如果你不想使用getline - 也就是说,当你不得不这么做的时候,你想把重物作为练习

make a buffer (say 50 chars) with malloc
loop
   get 1 char
   end of line? -> done
   buffer full ?
      use realloc to make bigger buffer
   put 1 char in buffer