LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   "segmentation fault: 11" with sprintf in C (https://www.linuxquestions.org/questions/programming-9/segmentation-fault-11-with-sprintf-in-c-4175547006/)

savio 07-02-2015 05:36 AM

"segmentation fault: 11" with sprintf in C
 
Hi,

I have problems with the strings size.
My program is the following:
Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

  FILE * fp;
  char input[20];
  char *str;

  printf("Enter the file name: ");
  scanf("%s", input);
  printf("The file name is %s\n", input);
  printf("Sizeof %s is %lu\n", input, sizeof(input));

  fp = fopen("file.txt", "w");
  fprintf(fp, "%s", input);
  fclose(fp);

  sprintf(str, "%s", input);
  puts(str);

  return 0;

}

Why fprintf works well whereas the sprintf causes the segmentation fault?
I noticed that changing the size of the input array from 20 to (at least) 41 solves the problem and sprintf works as well. Why?

firstfire 07-02-2015 06:12 AM

Hi.

Quote:

Why fprintf works well whereas the sprintf causes the segmentation fault?
The problem is the str pointer. You did not initialized it to point to a valid memory area, hence segfault when sprintf() tries to write to this (invalid) memory area.

You should allocate a big enough buffer before trying to write to it:
Code:

char *str = malloc(sizeof(char)*20);
or
Code:

char str[20]; // static allocation
Quote:

I noticed that changing the size of the input array from 20 to (at least) 41 solves the problem and sprintf works as well. Why?
Probably a compiler/operating system quirk. On my machine increasing length of input does not prevents segfault (fortunately).

Few links: C pointers and arrays, C memory management.

savio 07-02-2015 08:08 AM

It is true.
Thanks a lot!


All times are GMT -5. The time now is 09:54 PM.