没有参数无法执行,输入未正确解析

failing to execute without arguments, input not parsed correctly

在我下面的函数中,我试图从标准输入中读取几个句子,并在用户输入两次后处理它们。如图所示,我将内存动态分配给整个缓冲区(行集)。我 运行 喜欢:

zsh: illegal hardware instruction  ./myfunc

最小编译片段:

void myfunc(void) {

    int textsize = BUF_SIZE;
    char **lines = (char **) malloc(sizeof(char *) * textsize);
    int linecount = 0;
    char text[BUF_SIZE];

    while ((strcpy(text, fgets(text, BUF_SIZE, stdin))) != NULL) {
        if (text[0] == '\n') {
            break;
        }
        lines[linecount] = (char *) malloc(sizeof(char *) * strlen(text));
        strcpy(lines[linecount], text);
        linecount++;
    }
    for (int index = linecount - 1; index >= 0; --index) {
        fprintf(stdout, "%s", lines[index]);
        /* if line has newline stripped, else printf("%s", lines[index]);*/
    }

    free(*lines);
    exit(0);
}

在此内存分配中使用 textsize 的值

char **lines = (char **) malloc(sizeof(char *) * textsize);

没有意义。

在while循环的条件下使用strcpy

while ((strcpy(text, fgets(text, BUF_SIZE, stdin))) != NULL) {

也没有意义,因为 1) fgets 可以 return NULL 2) 如果 fgets 没有 return NULL 然后它已经用字符串填充了数组文本。

所以循环至少应该写成

while ( fgets(text, BUF_SIZE, stdin) != NULL) {

在此声明中

lines[linecount] = (char *) malloc(sizeof(char *) * strlen(text));

您需要分配 char 类型的对象数组而不是 char * 类型,并且分配的元素数应等于 tp strlen( text ) + 1.

这次通话

free(*lines);

仅释放指针指向的第一个分配的元素lines,但您需要释放所有分配的内存。

而这个调用在函数的最后

exit(0);

再次没有意义。至少你可以写

return;

或者只删除 exit.

的调用

该函数可以像下面的演示程序中所示的方式查找。

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

#define BUF_SIZE    100

void myfunc( void ) 
{
    char **lines = NULL;
    size_t linecount = 0;
    
    char text[BUF_SIZE];
    int success = 1;

    while ( success && fgets( text, BUF_SIZE, stdin ) != NULL && text[0] != '\n' ) 
    {
        char **tmp = realloc( lines, ( linecount + 1 ) * sizeof( char * ) );
        success = tmp != NULL;
        
        if ( success )
        {
            lines = tmp;
            lines[linecount] = malloc( ( strlen( text ) + 1 ) * sizeof( char ) );
            
            success = lines[linecount] != NULL;
            
            if ( success )
            {
                strcpy( lines[linecount], text );
                ++linecount;
            }
        }
    }
    
    if ( !success ) fputs( "Nor all input records were successfully stored\n", stdout );
    
    for ( size_t i = linecount; i != 0; ) 
    {
        fprintf( stdout, "%s", lines[--i]);
    }

    for ( size_t i = 0; i < linecount; ++i )
    {
        free( lines[i] );
    }
    free( lines );
}

int main(void) 
{
    myfunc();
    
    return 0;
}

如果要输入字符串

Hello
World 

那么输出将是

World 
Hello