Я пишу код, в котором вы должны заменить самое длинное и короткое слово в предложении, фактически не увеличивая / уменьшая строку.Я предполагал, что смогу создать новую строку и помещать текст из исходной строки, пока указатель не дойдет до указателя максимального слова (возвращаемого функцией nadji_max), а затем записать это слово из максимального указателя, продолжая копировать код изисходная строка, пока она не достигнет указателя на самое короткое слово и т. д. и т. д.
Все выходные данные соответствуют ожидаемым, но я получаю ошибки памяти в Valgrind.Честно говоря, я не очень хорошо понимаю вывод Valgrind, но он говорит мне, что в строке 2 есть ошибка памяти, которая кажется странной, когда строка 2 - мои включения.Я также попытался использовать malloc для строки и установить для него «strlen (s) * sizeof (char)», а затем освободить его, но это привело к утечкам памяти вместо ошибок памяти.Любые разъяснения, что вызывает мои ошибки памяти и как возможно исправить это / их?Спасибо
Мой код:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
char *nadji_max (char *s, int *maxvel)
{
int velicina = 0;
int max = 0;
char * maxpointer = NULL;
while (*s != '\0') {
velicina = 0;
while ((*s == '.' || *s == ',' || *s == '!' || *s == '?' || *s == ';' || *s == ' ') && *s != '\0') s++;
char *temp = s;
if (*s == '\0') break;
while (*s != '.' && *s != ',' && *s != '!' && *s != '?' && *s != ';' && *s != ' ') {
if (*s == '\0') break;
velicina++;
s++;
}
if (velicina > max) {
max = velicina;
*maxvel = velicina;
maxpointer = temp;
}
}
return maxpointer;
}
char *nadji_min (char *s, int *minvel)
{
int velicina = 0;
int min = INT_MAX;
char * minpointer = NULL;
while (*s != '\0') {
velicina = 0;
while ((*s == '.' || *s == ',' || *s == '!' || *s == '?' || *s == ';' || *s == ' ') && *s != '\0') s++;
char *temp = s;
if (*s == '\0') break;
while (*s != '.' && *s != ',' && *s != '!' && *s != '?' && *s != ';' && *s != ' ') {
if (*s == '\0') break;
velicina++;
s++;
}
if (velicina < min) {
min = velicina;
*minvel = velicina;
minpointer = temp;
}
}
return minpointer;
}
char *zamijeni_min_max (char *s)
{
char *pocetak = s;
int maxvel = 0, minvel = 0;
char *max = nadji_max(s, &maxvel);
char *min = nadji_min(s, &minvel);
char *pokmax = max;
char *pokmin = min;
//char *string = (char *) malloc(strlen(s) * sizeof(char));
char string [10000];
//strcpy(string, s);
char *pokstring = string;
char *pocstring = string;
while (*s != '\0') {
while ((*s == '.' || *s == ',' || *s == '!' || *s == '?' || *s == ';' || *s == ' ') && *s != '\0') {
*pokstring = *s;
s++;
pokstring++;
}
if (*s == '\0') break;
if (s == max) {
while (*pokmin != '.' && *pokmin != ',' && *pokmin != '!' && *pokmin != '?' && *pokmin != ';' && *pokmin != ' ' && *pokmin != '\0') {
*pokstring = *pokmin;
pokstring++;
pokmin++;
}
while (*s != '.' && *s != ',' && *s != '!' && *s != '?' && *s != ';' && *s != ' ' && *s != '\0') s++;
if (*s == '\0') {
*pokstring = '\0';
break;
}
} else if (s == min) {
while (*pokmax != '.' && *pokmax != ',' && *pokmax != '!' && *pokmax != '?' && *pokmax != ';' && *pokmax != ' ' && *pokmax != '\0') {
*pokstring = *pokmax;
pokstring++;
pokmax++;
}
while (*s != '.' && *s != ',' && *s != '!' && *s != '?' && *s != ';' && *s != ' ' && *s != '\0') s++;
if (*s == '\0') {
*pokstring = '\0';
break;
}
} else {
if (*s == '\0') break;
*pokstring = *s;
pokstring++;
s++;
}
}
return pocstring;
}
int main()
{
char recenica[] = "Ovo je primjer recenice sa dugackim, kratkim rijecima.";
printf ("'%s'", zamijeni_min_max(recenica));
}
Выход Valgrind:
==31760== Memcheck, a memory error detector
==31760== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==31760== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==31760== Command: bs_test_1
==31760== Parent PID: 31759
==31760==
==31760== Invalid read of size 1
==31760== at 0x3631247D0C: vfprintf (in /lib64/libc-2.12.so)
==31760== by 0x363124F069: printf (in /lib64/libc-2.12.so)
==31760== by 0x400C44: main (bs_test_1.c:124)
==31760== Address 0xffeffe4d0 is on thread 1's stack
==31760== 8112 bytes below stack pointer
==31760==
==31760== Invalid read of size 1
==31760== at 0x4A0CDB0: mempcpy (vg_replace_strmem.c:1517)
==31760== by 0x36312717DE: _IO_file_xsputn@@GLIBC_2.2.5 (in /lib64/libc-2.12.so)
==31760== by 0x363124806F: vfprintf (in /lib64/libc-2.12.so)
==31760== by 0x363124F069: printf (in /lib64/libc-2.12.so)
==31760== by 0x400C44: main (bs_test_1.c:124)
==31760== Address 0xffeffe4d0 is on thread 1's stack
==31760== 8032 bytes below stack pointer
==31760==
==31760== Invalid read of size 1
==31760== at 0x4A0CDBE: mempcpy (vg_replace_strmem.c:1517)
==31760== by 0x36312717DE: _IO_file_xsputn@@GLIBC_2.2.5 (in /lib64/libc-2.12.so)
==31760== by 0x363124806F: vfprintf (in /lib64/libc-2.12.so)
==31760== by 0x363124F069: printf (in /lib64/libc-2.12.so)
==31760== by 0x400C44: main (bs_test_1.c:124)
==31760== Address 0xffeffe4d2 is on thread 1's stack
==31760== 8030 bytes below stack pointer
==31760==
==31760==
==31760== HEAP SUMMARY:
==31760== in use at exit: 0 bytes in 0 blocks
==31760== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==31760==
==31760== All heap blocks were freed -- no leaks are possible
==31760==
==31760== For counts of detected and suppressed errors, rerun with: -v
==31760== ERROR SUMMARY: 109 errors from 3 contexts (suppressed: 4 from 4)