How can it be that variable with decimal assigned to it behaves not the same way as actual decimal does?

StackOverflow https://stackoverflow.com/questions/17209169

  •  01-06-2022
  •  | 
  •  

Question

The tricky line is char longest[] array initialization. If I put it like it is (char longest[lim]), the string returned to me after EOF is longer than lim, so I assume it doesn't work this way. But if I explicitly put 10 there (char longest[10]) — it works as I expect and return only 10 first characters of line.

What makes the difference, in this exact case, between int lim = 10; char longest[lim] and char longest[10]

#include <stdio.h>
#define MAXLINE 1000 //maximum input line size
//#define LIM 10

int getline(char line[], int maxline);
void copy(char to[], char from[]);

//print longest input line
main()
{
    int lim=10;


    int len; //current line length
    int max; //maximum length seen so far
    char line[MAXLINE]; //current input line
    char longest[lim]; //longest line saved here

    max = 0;
    while ((len = getline(line, MAXLINE)) > 0)
    {
        if (len > max)
        {
            max = len;
            copy(longest, line);
        }
    }
    if (max > 0) //there was a line
    {
        printf("Length: %d\n", max);
        printf("First %d characters of line: %s", lim, longest);
    }
    return 0;
}

//getline: read a line into s, return length
int getline(char s[], int lim)
{
int c, i;

for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
{
    s[i] = c;
}
if (c == '\n')
{
    s[i] = c;
    ++i;
}
s[i] = '\0';
return i;
}

//copy: copy 'from' into 'to'; assume to is bigh enough
void copy(char to[], char from[])
{
int i;

i = 0;
    while ((to[i] = from[i]) != '\0')
    {
        ++i;
    }
}
Was it helpful?

Solution

type name[10] is Fixed array declaration.

type name[exp] is Variable-length array.

Allocation is performed every time you encounter this declaration (in block) is from C99 variable-length arrays. Size is fixed after it is once formed.

So, the behavior of the case, such as access to outside the bounds of the array in code like the example is undefined.

OTHER TIPS

If you write a value that's too long to an array, you get "undefined behaviour". Anything can happen. You program might crash, or it might silently do the wrong thing, or it might even appear to work. Changing anything else in your program can change what happens.

This is also a security vulnerability - if an attacker can control the value that's written, they can probably make your program do anything they want.

Short version: Before you write a string to an array, you MUST make sure it'll fit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top