How come my code works? Seriously. :)
Hello.
The following code asks the user to enter a couple of words and then sorts them alphabetically. Not much and it does the job. However, just to see what happens, I didn't make enough room for the null character while declaring the word array and when using malloc. Still, everything seems to be working properly and I just wonder why.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LIMIT 8
int wcompare(const void *p, const void *q);
int rline(char rword[], int i);
int main(void)
{
int i, n = 0;
char *words[LIMIT];
char word[LIMIT]; // Should have been: LIMIT + 1?
for (;;) {
printf("Word: ");
rline(word, LIMIT);
if (*word == '\0')
break;
words[n] = malloc(strlen(word)); // Should have been: strlen(word) + 1?
strcpy(words[n++], word);
}
qsort(words, n, sizeof(char *), wcompare);
printf("Words: ");
for(i = 0; i < n; i++)
printf("%s ", words[i]);
printf("\n");
return 0;
}
int wcompare(const void *p, const void *q)
{
return strcmp(*(char **)p, *(char **)q);
}
int rline(char rword[], int i)
{
int ch, j = 0;
while ((ch = getchar()) != '\n')
if (j < i)
rword[j++] = ch;
rword[j] = '\0';
return j;
}
A typical session might look like this:
Code:
assiduus@ubuntu:~$ cc assiduus.c
assiduus@ubuntu:~$ ./a.out
Word: assiduus
Word: tmptmptmp
Word: blahblahblah
Word:
Words: assiduus blahblah tmptmptm
Where I'd suspect the program to crash is within the rline function when "rword[j] = '\0';" assigns \0 to the *nineth* element of the word array. The second questionable piece of code is when malloc doesn't allocate enough memory and the code still works flawlessly. Btw, I have no *real* programming experience so there's probably something obvious I'm missing but I just don't get it at the moment.