1

can you please tell me what is wrong with the following input process?

the input should be a string length and then the string itself.

something like "5 vlady"

It works just fine, but valgrind (memory leakage tool) tell the following exception:

Address 0x51ef184 is 0 bytes after a block of size 4 alloc'd

Her's the code:

unsigned int n;
char* string;

printf("Enter your string:\n");
scanf("%d", &n);
string = (char*)calloc((n),sizeof(char));
scanf("%s", string);

Thanks!

hmjd
  • 120,187
  • 20
  • 207
  • 252
vlady
  • 477
  • 1
  • 7
  • 14

1 Answers1

4

The posted code is writing one byte beyond the allocated memory as scanf("%s") appends a terminating null character. Description for format specifier s from section 7.19.6.2 fscanf function of the C99 standard:

If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically.

Therefore allocate n + 1 bytes.

Other:

  • always check the result of IO operations to ensure variables have been assigned a value:

    /* 'scanf()' returns number of assignments made.
       Use '%u' for reading an unsigned int. */
    if (scanf("%u", &n) == 1)
    {
    }
    
  • prevent buffer overrun by limiting the number of bytes consumed by scanf() by using the %Ns format specifier, where N is the number characters to read. In this case, the format specifier would need constructed, using sprintf() for example. Another option is to use fgets() but this does not stop reading when white space is encountered.

  • Do I cast the result of malloc?

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252