2016-02-29 16 views
8

Ho aggiunto due caratteri in più all'inizio della stringa e non riesco a capire perché. I personaggi non appaiono nemmeno nel codice. Sono in perdita qui. Questo è il mio codice:Caratteri extra aggiunti all'inizio della stringa?

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

char *chars; 

char* vector(char input, char *newlist); 

int main(){ 

    char *input, *out = "Input: "; 

    printf("Enter characters: ");     
    while(1){ 
     char i = getchar();       //get input 
     if(i == '\n'){ 
      break;         //detect a return key 
     } else{ 
      input = vector(i, input);    //call vector 
     } 
    } 

    char * print = (char *)malloc(1 + strlen(input) + strlen(out)); 
    strcpy(print, out);        //concat the strings 
    strcat(print, input); 

    printf("\n%s", print);       //print array 

    free(print); 
    free(input); 
    free(chars); 

    return 0;          //exit 
} 

char* vector(char in, char *newlist){ 

    int length = strlen(newlist);     //determine length of newlist(input) 

    chars = (char*)calloc(length+2, sizeof(char)); //allocate more memory 
    strcpy(chars, newlist);       //copy the array to chars 
    chars[length] = in;        //appened new character 
    chars[length + 1] = '\0';      //append end character 

    return chars; 
} 

Per qualche ragione, il codice produce questo:

Enter characters: gggg 

Input: PEgggg 

Quando si dovrebbe produrre questo:

Enter characters: gggg 

Input: gggg 
+3

A cosa punta 'input'? – immibis

+0

Nota a margine: dato che 'chars' è una variabile globale, non c'è alcun punto in 'return chars;'. –

+0

@barakmanos sarebbe meglio rimuovere la variabile globale e renderla locale a 'vector' –

risposta

5

È passata inizializzata input-vector() e usate così, hai invocato il comportamento non definito .

Provare a cambiare char *input a char *input = "".

Rimuovere anche free(chars); o si verificherà un problema di doppio-libero.

+0

C'è anche una perdita di memoria con la 'memoria calloc'd nel vettore. –

+1

Un altro problema è che la memoria allocata da 'calloc' non viene mai liberata. Il modo migliore per farlo sarà usare 'vector' per chiamare' free (newlist) '; quindi il valore iniziale di 'input' deve essere' calloc (1,1); ', o' NULL' con 'vector()' che ha un caso speciale per gestire input nulli. –

1

L'inizializzazione del char * è mancante e quindi porta a un comportamento non definito. Pls inizializza il carattere *

5

Penso che tu abbia uno o più campi non inizializzati. Ottengo questi avvertimenti quando provo a compilare:

$ clang -Weverything vector.c 
vector.c:15:18: warning: implicit conversion loses integer precision: 'int' to 'char' [-Wconversion] 
     char i = getchar();       //get input 
      ~ ^~~~~~~~~ 
vector.c:19:31: warning: variable 'input' may be uninitialized when used here [-Wconditional-uninitialized] 
      input = vector(i, input);    //call vector 
           ^~~~~ 
vector.c:11:16: note: initialize the variable 'input' to silence this warning 
    char *input, *out = "Input: "; 
      ^
       = NULL 
vector.c:40:33: warning: implicit conversion changes signedness: 'int' to 'unsigned long' [-Wsign-conversion] 
    chars = (char*)calloc(length+2, sizeof(char)); //allocate more memory 
        ~~~~~~ ~~~~~~^~ 
vector.c:38:18: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32] 
    int length = strlen(newlist);     //determine length of newlist(input) 
     ~~~~~~ ^~~~~~~~~~~~~~~ 
vector.c:5:7: warning: no previous extern declaration for non-static variable 'chars' [-Wmissing-variable-declarations] 
char *chars; 
    ^
5 warnings generated. 

Quando uso Asan what is ASan?, ottengo il seguente errore:

$ echo 1 2 3 | ./a.out 
Enter characters: 
================================================================= 
==23718==ERROR: AddressSanitizer: attempting double-free on 0x60200000ef70 in thread T0: 
    #0 0x4a5f4b in free /home/development/llvm/3.7.0/final/llvm.src/projects/compiler-rt/lib/asan/asan_malloc_linux.cc:30:3 
    #1 0x4cd631 in main (/home/brian/src/so/a.out+0x4cd631) 
    #2 0x7f3b94ef5a3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20a3f) 
    #3 0x4174c8 in _start (/home/brian/src/so/a.out+0x4174c8) 

0x60200000ef70 is located 0 bytes inside of 7-byte region [0x60200000ef70,0x60200000ef77) 
freed by thread T0 here: 
    #0 0x4a5f4b in free /home/development/llvm/3.7.0/final/llvm.src/projects/compiler-rt/lib/asan/asan_malloc_linux.cc:30:3 
    #1 0x4cd5fa in main (/home/brian/src/so/a.out+0x4cd5fa) 
    #2 0x7f3b94ef5a3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20a3f) 

previously allocated by thread T0 here: 
    #0 0x4a63b4 in calloc /home/development/llvm/3.7.0/final/llvm.src/projects/compiler-rt/lib/asan/asan_malloc_linux.cc:56:3 
    #1 0x4cd67c in vector (/home/brian/src/so/a.out+0x4cd67c) 
    #2 0x4cd57b in main (/home/brian/src/so/a.out+0x4cd57b) 
    #3 0x7f3b94ef5a3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20a3f) 

SUMMARY: AddressSanitizer: double-free /home/development/llvm/3.7.0/final/llvm.src/projects/compiler-rt/lib/asan/asan_malloc_linux.cc:30:3 in free 
==23718==ABORTING 
6

Tutti i punti @MikeCat si dicono sono corretti, solo per aggiungere che la memoria allocata da calloc non viene liberato che porta ad una perdita di memoria. È possibile free come detto da @MM in un commento, ma per la prossima volta, per evitare perdite di memoria, è possibile utilizzare valgrind:

Let's take your program, as hash.c . Got to the command line and compile it, for eg :

gcc hash.c -Wall 

If your program compiles successfully, an executable or out file will appear. As we have not specified the name of the executable, it's default name will be a.out . So let's run it with valgrind :

valgrind -- leak-check=full ./a.out 

This will run executable, along with valgrind, and if there is a memory leak, it will show it when the executable ends.


If you do not have valgrind installed, you can install it from here .

0

È necessario eliminare gratuito (stampa) e assegnare alla pointers.First chiamato doppia free e l'ultimo ha causato il core dumped.Io lavoro su ubuntu e la mia versione gcc è 4.8.4

Problemi correlati