A
Army1987
The program below works correctly, but dumps core if I add
free(str); before return 0;. The error message is somewhat more
colorful than just "Segmentation fault" (several lines long) and
seems to say "Invalid pointer".
I know free() causes UB is passed a pointer which was not returned
by an *alloc() function, but here I never change the value of str
after the call to malloc()... What is wrong?
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char *b = "0123456789abcdefghijklmnopqrstuvwxyz_";
int main(int argc, char **argv)
{
char *a = "Chuck Norris's tears can cure cancer. "
"Too bad he's never cried. Ever.";
size_t r=0, len = strlen(a);
char *t, *str;
size_t ch = argv[1] ? (str=argv[1],(t = strchr(b,*str++))
&& (r += t-b),
r *= strlen(b),
(t = strchr(b,*str)) && (r += t-b), r) : 0;
if (ch <= len) {
putchar(a[ch]);
ch++;
fflush(stdout);
len = strlen(argv[0]);
str = malloc(len+4);
if (!str)
exit(EXIT_FAILURE);
strcpy(str, argv[0]);
str[len] = ' '; str[len+1] = b[ch/strlen(b)];
str[len+2] = b[ch%strlen(b)]; str[len+3] = 0;
system(str);
} else
putchar('\n');
return 0;
}
free(str); before return 0;. The error message is somewhat more
colorful than just "Segmentation fault" (several lines long) and
seems to say "Invalid pointer".
I know free() causes UB is passed a pointer which was not returned
by an *alloc() function, but here I never change the value of str
after the call to malloc()... What is wrong?
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char *b = "0123456789abcdefghijklmnopqrstuvwxyz_";
int main(int argc, char **argv)
{
char *a = "Chuck Norris's tears can cure cancer. "
"Too bad he's never cried. Ever.";
size_t r=0, len = strlen(a);
char *t, *str;
size_t ch = argv[1] ? (str=argv[1],(t = strchr(b,*str++))
&& (r += t-b),
r *= strlen(b),
(t = strchr(b,*str)) && (r += t-b), r) : 0;
if (ch <= len) {
putchar(a[ch]);
ch++;
fflush(stdout);
len = strlen(argv[0]);
str = malloc(len+4);
if (!str)
exit(EXIT_FAILURE);
strcpy(str, argv[0]);
str[len] = ' '; str[len+1] = b[ch/strlen(b)];
str[len+2] = b[ch%strlen(b)]; str[len+3] = 0;
system(str);
} else
putchar('\n');
return 0;
}