-3

I am having some trouble understanding how memory is allocated to sir[i]. From what I understand (char*)malloc(sizeof(char)) should only allocate space for one character, but when I run the code it can read any word, regardless of length. Can someone plese explain how/why does this happen?

void read(char **sir,int **ln,int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        printf("Read word %d: ",i+1);
        sir[i]=(char*)malloc(sizeof(char));
        fflush(stdin);
        scanf("%s",sir[i]);
        ln[i]=(int*)malloc(sizeof(int));
        *(ln[i])=strlen(sir[i]);
    }
}
CoderPi
  • 12,423
  • 4
  • 31
  • 59

3 Answers3

3

You write beyond the boundary of the memory you allocated. This is undefined behavior, and you are unlucky enough that it seemed to "work".

StoryTeller - Unslander Monica
  • 159,632
  • 21
  • 358
  • 434
1

It's called a buffer overflow resulting in undefined behavior. It may or may not crash your problem, but it is a security hole nonetheless.

scanf with %s without a maximum length specified is always a security hole just like gets() and should not be used!

BTW: sizeof char is guaranteed to be 1 so you don't need to specify it - just use the number of chars you need; multiplying by sizeof char is likely to be optimized away by your compiler.

ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
0

From what I understand (char*)malloc(sizeof(char)) should only allocate space for one character

Thats correct. malloc in this case returns a pointer to 1 byte of allocated memory.

fflush(stdin);

Is undefined. At this point, anything may happen.

scanf("%s",sir[i]);

Is also undefined. Again, at this point anything may happen, from crashing your program with a segfault to it seemingly working.

Magisch
  • 7,198
  • 9
  • 38
  • 51