Reputation: 23
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
Upvotes: 1
Views: 8488
Reputation: 14452
There are few things that are needed to address compiler warning:
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[]);
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.
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));
Upvotes: 2