`System.Nullreferenceexception` in C

Asked

Viewed 40 times

0

Running the following code shows the error System.NullReferenceException in function call SubString

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

//
//  Implementado o metodo Substring para retornar um nova area de memoria
//  com os dados formatados conforme possição informada.
//
void            SubString
            (
                char        *ls_retorno,
                char        *as_origem,
                int         an_inicio,
                int         an_quantidade
            )
{

    //
    //  Variaveis de controle.
    //
    int
    ln              =   0,
    ln_cotador      =   0;

    //
    //  Se posição inicial menor que 0 ou
    //  Se posição inicial muito exagerada...
    //
    if  (an_inicio  <   0)
    {
        an_inicio   =   0;
    }

    //
    //  Obtem os caracteres desejados
    //
    for (   
            ln      =   an_inicio;
            ln      <   an_quantidade   +   an_inicio;
            ln++
        )
    {
        ls_retorno[ln_cotador++]    =   as_origem[ln];
    }

    //
    //  Elimina todos os espacos nao ocupados.
    //
    ls_retorno[ln_cotador]      =   '\0';

    printf("Resultado Funcao: >%s<",    ls_retorno);

    //
    //  Retorna a informacao tratada.
    //
//  return  (ls_retorno);
}

int main()
{

    //
    //  Cria a palavra chave e o valor.
    //
    char
    *ls_palavrad;
    char
    *ls_valord;

    //
    //  Aloca a espaco em memoria
    //
    ls_palavrad     =   (char*)malloc(30*sizeof(char));         
    ls_valord       =   (char*)malloc(200*sizeof(char));        

    //
    //  Limpa o buffer
    //

    ls_palavrad     =   (char*) NULL;
    ls_valord       =   (char*) NULL;


    printf(">Chamada<");

    SubString(ls_palavrad,  "mensagem=Sequencial invalido", 1,  5);

    printf("Retorno: >%s<", ls_palavrad);


    return 0;
}
  • As a curiosity, you don’t like to use spaces when writing code?

  • use only tabs

  • And why do you use line breaking in ifs and other structures? Don’t you think it gets harder to read the code like this?

  • sorry if it makes it harder to understand like that, and matter of custom even

  • You allocate memory for the variable ls_palavrad and then you "clean up" her buffer with (char*) NULL. When you perform SubString(ls_palavrad, ..., ... you try to access: ls_retorno[ln_cotador++] as a result of NullReferenceException.

  • but if I just create and do the malloc gets junk, some hint how to fix it?

Show 1 more comment

1 answer

1


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

void SubString (char *ls_retorno,  char *as_origem,  int an_inicio, int an_quantidade  )  {
    int ln = 0, ln_cotador = 0;

    if (an_inicio < 0)
        an_inicio = 0;

    for (ln = an_inicio; ln < an_quantidade + an_inicio; ln++)
        ls_retorno[ln_cotador++] = as_origem[ln];

    ls_retorno[ln_cotador] = '\0';

    printf("Resultado Funcao: >%s<", ls_retorno);
}


int main() {
    char *ls_palavrad;
    char *ls_valord;

    ls_palavrad = (char*) malloc(30 * sizeof(char));
    ls_valord = (char*) malloc(200 * sizeof(char));

    printf(">Chamada<");

    SubString(ls_palavrad, "mensagem=Sequencial invalido", 1, 5);

    printf("Retorno: >%s<", ls_palavrad);

    free(ls_palavrad);
    free(ls_valord);

    ls_palavrad = NULL;
    ls_valord = NULL;

return 0;

}
  • 1

    but if I just create and do the malloc gets garbage

  • A pointer stores garbage only if it is declared without being initialized with a correct value, or when it is shifted by the function free without being set as NULL subsequently.

  • where it happens there?

  • The correct way to use pointers is to allocate using malloc() as you did in main() and AFTER you have used pointers you should use the free() function to free the memory. If you use malloc and then set the pointers to NULL , which is what you did, you won’t be releasing the memory. The bytes allocated by malloc will continue in memory and you will not be able to access that address anymore because you lost them when you made the pointers equal to NULL

  • so I’m doing this

  • even in that print right there after the function already prints garbage

  • I’ll edit my answer with the code, just a moment.

  • @Lucasfernandes checks the answer

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.