The following C program will print the shortest and longest string as t[0] and t[n-1]. However, when I run this code, it says there is a memory problem. What is wrong with my code?
The problem is the last two lines, with "strcpy".
#include <stdio.h>
#include <string.h>
void fx (char* t[], int n);
int main(void)
{
char* t[] = {"horse", "elephant", "cat", "rabbit"};
int n;
n = sizeof( t )/ sizeof( t[0] );
fx(t, n);
printf("shortest is %s, longest is %s\n", t[0], t[n-1]);
}
void fx (char* t[], int n)
{
char st[50], lt[50];
strcpy(lt,t[0]);
strcpy(st,t[0]);
for (int i=0; i<n; i++)
{
if (strlen(t[i]) < strlen(st))
strcpy(st,t[i]);
if (strlen(t[i]) > strlen(lt))
strcpy(lt,t[i]);
}
strcpy( t[0], st);
strcpy( t[n-1], lt);
}
Both strcpy()s,
strcpy( t[0], st);
strcpy( t[n-1], lt);
are wrong! t[i] points to const string literals - not modifiable, which causes undefined behavior at runtime.
char* t[] = {"horse", "elephant", "cat", "rabbit"};
declares an array of pointers to string literals. String literals may be placed in read-only memory and cannot be modified. The final strcpy lines in fx are trying to write to read-only memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With