内存分配和输入的问题(C)

问题描述 投票:0回答:1

我的目标是读取用户的输入并将用户给出的每个单词存储在一个动态分配的数组中,我称之为“str”。但是,我有两个问题。第一,在函数 leArgs 中读取第一个参数之后的参数时,如果我尝试使用 arg[agrs] (args > 0) 打印它,它会给我 SEGFAULT。其次,如果我只给出一个单词,leArgs 可以工作,但它不会在“str”中存储任何内容,在我尝试打印它的第一个参数后给我 SEGFAULT。

如果我感到困惑或不够清楚评论,我会重写它!我的代码:

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


    #define INVERSO "inverso"   /* String representativa da chave para impressão
                                do percurso duma carreira por ordem inversa */
    #define LEN_INVERSO 8       /* Comprimento da chave representativa */

    #define TRUE 1  /* verdadeiro */
    #define FALSE 0 /* falso */

    #define FIM_LINHA -1 /* fim de linha */
    #define NOTVALID -1 /* não é valido*/

    #define BUFFER 65535 

    enum arg {PRIMEIRO, SEGUNDO, TERCEIRO, QUARTO, QUINTO};


    int is_space ( int c ) {
        return (c == '\t' || c == ' ' || c == '\n'); 
    }

    /* Recebe um char e retorna True se for um fim de linha
    e false caso contrario */
    int NotEndOfLine ( char character ) {
        return character != '\n';
    }

    int leNome ( char *buff ) {
        int character, aspas = FALSE, i = 0;

        while ( is_space (character = getchar()) ) {
            if ( !NotEndOfLine(character) )
                return FIM_LINHA;
        }

        do {
            if (character == '"')
                aspas = (aspas == FALSE) ? TRUE : FALSE;
            else
                buff[i++] = character;

        } while ( !is_space(character = getchar() ) || aspas == TRUE );

        buff[i++] = '\0';

        return !NotEndOfLine ( character );
    }

    int leArgs ( char **arg ) {
        int num_args = 0, args = PRIMEIRO, lenght, endline;
        char buff[BUFFER];


        do {
            endline = leNome( buff );
            printf("Run: %d\n" , args);
            if ( endline == FIM_LINHA )
                return num_args;

            arg = (char**) realloc ( arg, sizeof (char*) * (++num_args)) ;

            lenght = strlen(buff);

            arg[args] = (char *) malloc (sizeof (char) * (lenght + 1) );
            strcpy( arg[args] , buff );
            
            printf("buff:%s arg:%d num_args:%d\n", buff, args, num_args);
            printf( "Argumento: %s\n", arg[args] );
            putchar('\n');
            args++;

        } while ( endline == FALSE ) ;

        return num_args;
    }

    int main(){
        int i, num_args;
        char **str = NULL;
        num_args = leArgs( str );

        printf( "%s ", str[0]);

        puts( "sucesso ");

        for(i = 0; i < num_args; i++){
            printf("i:%d",i);
            printf("%d:%s\n",i,str[i]);
        }

        return 0;
    }
c segmentation-fault dynamic-memory-allocation realloc
1个回答
1
投票

您正在将指针

str
按值传递给函数
leArgs

    char **str = NULL;
    num_args = leArgs( str );

这意味着该函数处理原始指针的副本。在函数内更改副本不会更改原始指针。

您需要通过指向它的指针通过引用传递它。

函数应该这样声明

int leArgs ( char ***arg );

并称呼

num_args = leArgs( &str );

在函数中你至少需要像这样写

*arg = (char**) realloc ( *arg, sizeof (char*) * (++num_args));

虽然使用中间指针会更安全,例如

char **tmp = realloc ( *arg, sizeof (char*) * (++num_args));

if ( rmp != NULL ) *arg = tmp;
© www.soinside.com 2019 - 2024. All rights reserved.