1

I am trying to make string copy command but I am getting the compilation warning (see the title) when compiling the program. If I compile the code without -Wall option than it gives me the correct output but I want to compile it with -Wall and get no warnings. How do I solve my issues? I already googled it but I didn't understand it.

When I initialise str2 to NULL or 0 it gives me seg fault.

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

void my_strcpy(char *dest[], const char *src[]);

int main(){

  char *str1, *str2;
  int i;

  printf("What is the longest length of a string that you will enter?");
  scanf("%i",&i);

  str1=malloc(i * sizeof(char));
  if (str1 == NULL){
    printf("\n malloc failed to allocate enough memory!\n");
    return 1;
  }

  printf("Enter a string: ");
  scanf("%s", str1);

  my_strcpy(str2,str1);
  printf("%s \n", str1);
  return 0;
}

void my_strcpy(char *dest, const char *src)
{
  int i;

  for(i=0; src[i]!='\0'; i++)
    dest[i]=src[i];
}

I expect the output to display just one string for example:

text entered: hello world

output:

hello

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
static_sid
  • 23
  • 1
  • 3
  • Consider posting the full warning, it will save time for everyone. – dash-o Nov 12 '19 at 05:50
  • BTW, you will rarely if ever want to use `%i` with scanf. Use `%d`. – Antti Haapala -- Слава Україні Nov 12 '19 at 07:03
  • 1
    This turns into a code review but still: For a real program it is indispensable to **check whether `scanf("%i",&i);` was successful.** The `scanf` family of functions returns the numbers of items read successfully. In this case it must be 1, or else `i` will have an arbitrary value (and the program formally exposes undefined behavior, even though it will "work" on PCs, but with some unknown value for i). You should also check the input for values which seem too large or <= 0. Then **use `scanf` with a [dynamically determined field width](https://stackoverflow.com/a/28460098/3150802).** – Peter - Reinstate Monica Nov 12 '19 at 08:47

1 Answers1

2

There are few things that are needed to address compiler warning:

  1. Function prototype for my_strcpy. Considering matching the protytype to the implementation: void my_strcpy(char *dest, const char *src);, and NOT void my_strcpy(char *dest[], const char *src[]);

  2. Allocation for str2. It is declared as a pointer, but no assignment to a space was done. Consider adding str2 = malloc(i+1); or similar.

  3. Allocation for str1 (run time error, not compiler warning). Remember to add space for the terminal NUL bytes: str1=malloc((i+1) * sizeof(char)); instead of str1=malloc(i * sizeof(char));

dash-o
  • 13,723
  • 1
  • 10
  • 37