#K&R C (second edition) causes segfault?

1 messages · Page 1 of 1 (latest)

icy ibex
#
#include <stdio.h>                                                  
#define MAXLINE 100

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

int main() {
  int len;
  int max;
  char line[MAXLINE];
  char longest[MAXLINE];

  max = 0;
  while((len = getline(line, MAXLINE)) > 0){
    if (len > max) {
      max = len;
      copy(longest, line);
    }
  if(max > 0) 
      printf("%s", longest);
  }
  return 0;
}

int getline(char s[], int lim) {
  int c, i;

for(int 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;
}

void copy(char to[], char from[]) {
  int i;

  i = 0;
  while((to[i] = from[i]) != '\n') {
    ++i;
  }
}```
Pretty much, this code segfaults, it comes from 1.9 Character arrays.
When I remove `s[i] = '\0'` it compiles and runs fine.
Commands I've used for compiling is `cc characterarrays.c -std=c99`
atomic cryptBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

icy ibex
#

okay okay, does old C99 have \n\0 at the end of character arrays, and modern C only have \0?

sage marsh
#
  int c, i;

for(int i = 0;```this is shadowing the outer `i`
pastel plover
sage marsh
#

so when you use i outside of the loop you're actually just accessing an indeterminate value

#

also I'm confused why copy is using \n as the terminator

#

s[i] == c; this line is also wrong

sage marsh
#

(i.e. fixing the above stuff mentioned, inputting more than 98 characters on a single line still crashes)

#

or if you just don't send a new line at the end