0

While trying this code in C, I'm seeing garbage value in main method. What mistake I'm doing?

I hope that I should use "%s" in main method also but seems like wrong. Why?

#include <stdio.h>
#include <stdlib.h>
char* minimumMultiple(int num);

int main(void) {
// your code goes here
printf("%s", minimumMultiple(13)); // prints  -  *p·ä…d¿“¿Eƒ (GARBAGE) - WHY?
return 0;
}

char* minimumMultiple(int num) {
int chars1s = 1, rem = 1;
while (rem != 0) {
    rem = (rem*10+1) % num;
    chars1s++;
}
char chars[chars1s];
int i;
printf("%d\n", chars1s); // prints 6 
for (i=0;i<chars1s;i++) {
    chars[i] = '1';
}
chars[i] = '\0';
    printf("%s\n",chars); // prints "111111"
return chars;
}
unknown_boundaries
  • 1,482
  • 3
  • 25
  • 47
  • 3
    `chars` is local storage which should not be returned for further usage outside of its scope ( as the stack can and will overwrite it ) – amdixon Aug 16 '15 at 10:41
  • 1
    `chars[i] = '\0';` writes one past the array invoking Undefined Behavior. Fix it by changing `char chars[chars1s];` to `char chars[chars1s + 1];` – Spikatrix Aug 16 '15 at 10:56

1 Answers1

2

You are returning an address for locale variable chars in minimumMultiple.

test_c.c:25:5: warning: function returns address of local variable [-Wreturn-local-addr]
     return chars;

You should define chars as a pointer.

 char *chars = malloc(chars1s + 1);
melpomene
  • 84,125
  • 8
  • 85
  • 148
Assem
  • 11,574
  • 5
  • 59
  • 97