2010-06-14 14 views
7

Przydzielam tablicę 2d i używam zestawu memset, aby wypełnić go zerami."Używanie niezainicjowanej wartości" pomimo memsetu

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

void main() { 
    int m=10; 
    int n =10; 
    int **array_2d; 
    array_2d = (int**) malloc(m*sizeof(int*)); 
    if(array_2d==NULL) { 
     printf("\n Could not malloc 2d array \n"); 
     exit(1); 
    } 
    for(int i=0;i<m;i++) { 
     ((array_2d)[i])=malloc(n*sizeof(int)); 
     memset(((array_2d)[i]),0,sizeof(n*sizeof(int))); 
    } 


    for(int i=0; i<10;i++){ 
     for(int j=0; j<10;j++){ 
      printf("(%i,%i)=",i,j); 
      fflush(stdout); 
      printf("%i ", array_2d[i][j]); 
     } 
     printf("\n"); 
    } 
} 

Następnie używam valgrind [1], aby sprawdzić błędy pamięci. Dostaję następujący błąd: Conditional jump or move depends on uninitialised value(s) dla linii 24 (printf("%i ", array_2d[i][j]);). Zawsze uważałem, że memset to funkcja inicjująca tablice. Jak mogę pozbyć się tego błędu?

Dzięki! Wyjście

Valgrind:

==3485== Memcheck, a memory error detector 
==3485== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al. 
==3485== Using Valgrind-3.5.0-Debian and LibVEX; rerun with -h for copyright info 
==3485== Command: ./a.out 
==3485== 
(0,0)=0 (0,1)===3485== Use of uninitialised value of size 4 
==3485== at 0x409E186: _itoa_word (_itoa.c:195) 
==3485== by 0x40A1AD1: vfprintf (vfprintf.c:1613) 
==3485== by 0x40A8FFF: printf (printf.c:35) 
==3485== by 0x8048724: main (playing_with_valgrind.c:39) 
==3485== 
==3485== 
==3485== ---- Attach to debugger ? --- [Return/N/n/Y/y/C/c] ---- 
==3485== Conditional jump or move depends on uninitialised value(s) 
==3485== at 0x409E18E: _itoa_word (_itoa.c:195) 
==3485== by 0x40A1AD1: vfprintf (vfprintf.c:1613) 
==3485== by 0x40A8FFF: printf (printf.c:35) 
==3485== by 0x8048724: main (playing_with_valgrind.c:39) 

[1] valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes --db-attach=yes ./a.out

[GCC-cmd] gcc -std=c99 -lm -Wall -g3 playing_with_valgrind.c

Odpowiedz

14

w linię:

/* sizeof(n*sizeof(int)) retuns a value of type size_t. 
    This means you are initializing only sizeof(size_t) of the array. */ 
memset(((array_2d)[i]),0,sizeof(n*sizeof(int))); 

Powinno być:

memset(((array_2d)[i]),0, n*sizeof(int)); 
+0

Naprawdę dobre oczy! –

+0

Argh! Dziękuję Ci bardzo. Przyjmuję twoją odpowiedź tak szybko, jak to możliwe. – Framester

+0

Dobrze zauważył ... trudno to zobaczyć – Spudd86

4

Zmień stwierdzenie:

memset(((array_2d)[i]),0,sizeof(n*sizeof(int))); 

do:

memset(((array_2d)[i]),0,n*sizeof(int)); 

Nie powinno się robić sizeof tam. Po prostu zwróci rozmiar typu zmiennej, która nie jest tym, czego potrzebujesz.

Powiązane problemy