1

After going through multiple examples of passing a string by value in C, I still don't understand why the following code does not work

int main(void){
  char *fileList;
  strcpy(fileList,"This is a test line\n");
  char type = 'F';

  if(checkFileList(fileList, type)){
    printf("Proper File list\n");
  }
  else{
    printf("Improper File list\n");
  }

}


int checkFileList(char *string, char type){
  // Do something with string
}

This program works if I define the variable fileList in the main function as-

char fileList[128];

But I can't provide a fixed size to this string as I get the string only at runtime and hence don't know how long it'll be.

What am I doing wrong here? Please note that I don't want to pass the string by reference as I'll be changing the string in the function and don't want this to be reflected in the original string.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Gaurav Suman
  • 515
  • 1
  • 3
  • 17
  • 1
    And just what is "pass string by value"? There's no such thing in C. – Lundin Jun 26 '15 at 14:11
  • Maybe I don't know the correct terminology, but I'd like the called program to use a copy of the string, and not modify the original one – Gaurav Suman Jun 26 '15 at 14:17
  • 1
    @gaurav please don't edit and change a question in a way that makes existing asnwers appear invalid. Always ***add*** the update **without removing** the original one. Hope i'm understood. – Sourav Ghosh Jun 26 '15 at 14:22
  • Sorry about that. I did add an explanation on why I changed the original post, maybe that comment is not shown here. Anyways, I know what not to do from now on :) – Gaurav Suman Jun 26 '15 at 14:37
  • If it is just not to modify the string: How about a `const char *` argument? You should have the strings stored somewhere already. – too honest for this site Jun 26 '15 at 14:53

2 Answers2

3

In your code

char *fileList;
strcpy(fileList,"This is a test line\n");

invokes undefined behaviour , as , fileList is used uninitialized.

You need to allocate memory to fileList before using it. Maybe malloc() and family of functions will help you into that. Also, read about free().

FWIW,

This program works if I define the variable fileList in the main function as-
char fileList[128];

because, the fileList is an array here and the memory allocation is already done by the compiler. So, it is ok to use that.


BTW "Passing string by value" is misuse of the terms. C uses pass-by-value for any function parameter passing.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

In order to allocate the memory for the string at runtime you better get to know the size of the string first:

int main(void){
  const char *str = "This is a test line\n";
  int len = strlen(str);
  char *fileList = malloc(len);

  // then later you also have to take care for releasing the allocated memory:
  free(fileList);
}
Matthias
  • 3,458
  • 4
  • 27
  • 46