Home > Back-end >  print garbage value in c
print garbage value in c

Time:04-18

what i was trying to do is to count the number of alphanumerics and im using pointers . everything is working fine but when im trying to print the values its printing what i wanted garbage values because of the continuation of the memory it holds

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

 #define SIZE 10000 

 void printChar(int *p);

 int main(){

int *p,*new_p;
int c,i = 0,numOfAlNum = 0,numOfChar = 0;

p = (int*)malloc(SIZE * sizeof(int));

/*If memory cannot be allocated*/
if(p == NULL){
    printf("Error! memory not allocated\n");
    exit(0);
}
else
    printf("Memory successfully allocated\n");


printf("enter something\n");


while((c = getchar()) != '\n'){

    *(p   i) = c;
    i  ;
    /*Add Realloc to the loop*/
    new_p = realloc(p,(i 1)*sizeof(int));
    
    /*check for ability to allocate new memory*/
    if(new_p == NULL){
        printf("Error! memory not allocated\n");
        exit(0);
    }else{
        p = new_p;  
    }
    
    /*Check is alphanumeric*/
    if(isalnum(c)){
        numOfAlNum  ;
    }
    
    numOfChar  ;    
}


printf("The output is: \n");
for(i = 0; i < SIZE; i  ){
    printf("%s",(p i));
}
printf("\nNumber of Characters is %d\n",numOfChar);
printf("Number of Alpha-Numeric is %d\n",numOfAlNum);


 return 0;

}

EXAMPLE OF Expected OUTPUT : "hello world" WHAT IM GETTING IS: "hello world&^^^%^#" how do i get rid of the unnecessary values at the end ?

CodePudding user response:

how do i get rid of the unnecessary values at the end ?

Rather than print to the size of the allocation SIZE,
print the portion of the allocation that was assigned: numOfChar.

Use "%c" to print individual characters.
"%s" is for strings: null character terminated character arrays.

//for(i = 0; i < SIZE; i  ){
//  printf("%s",(p i));
//}

for(j = i; i < numOfChar; i  ){
  printf("%c",(p i));
}
  • Related