software_dude5050
software_dude5050

Reputation: 11

Exception thrown when using malloc() to create an array of characters

Essentially, I'm trying to create a program that simply takes in input from the user and then prints it, using dynamically allocated memory. Yes I know how to do this the simple way, but I'm attempting to get to grips with the intricacies of memory management in C. So what is wrong with this code? it runs without error but when I enter in a string into the command line it stops working and throws an exception at a hexadecimal address. Thank you in advance.

int main() {
  char *input;

  input = (char *)malloc(20 * sizeof(char)); 
  puts("Enter the string you wish to display"); 
  scanf_s("%s", input); 
  printf_s("%s", *input); 
  free(input);  
  return 0; 
}

Upvotes: 0

Views: 278

Answers (3)

alk
alk

Reputation: 70893

You are using scanf_s("%s", ... wrongly.

Verbatim from the docs:

The main difference between the more secure functions (that have the _s suffix) and the other versions is that the more secure functions require the size in characters of each c, C, s, S, and [ type field to be passed as an argument immediately following the variable.

So if input points to the 1st character of a sequence of 20 char then it should be:

  scanf_s("%s", input, 20); 

Lessons learned: If in doubt, (re-)read the documentation!

Upvotes: 1

Jabberwocky
Jabberwocky

Reputation: 50778

You probably want this:

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

int main() {
  char *input;

  input = malloc(20 * sizeof(char)); // (char *) is not needed here (but doesn't harm either)
  puts("Enter the string you wish to display");
  scanf("%s", input);
  printf("%s", input);  // *input is wrong here
  free(input);
  return 0;
}

Don't use the _s verions as they are not standard on every platform and more or less pointless, just use scanf and printf.

Upvotes: 1

pmdj
pmdj

Reputation: 23428

Your compiler should be warning you about this line:

printf_s("%s", *input);

If not, you need to enable an "all warnings" setting. (On gcc and clang, add -Wextra to the command line.)

Essentially, you have a mismatch between the type of the argument (char) and the type expected by the format string (const char*). *input dereferences the character pointer, and so evaluates to the first character in the string. "%s" expects a pointer to a nul-terminated array of characters.

It should work if you remove the *:

printf_s("%s", input);

Upvotes: 2

Related Questions