为什么我的程序跳过cicle? ç
问题描述:
即时试图代码,将字符串分割到多个的功能,我知道我有很多的分配空间没有释放,我只是测试此位,但Valgrind的显示我为什么我的程序跳过cicle? ç
Conditional jump or move depends on uninitialised value(s)
==25613== at 0x4C2DB3C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==25613== by 0x40090C: split (strutil.c:32)
==25613== by 0x400A00: main (strutil.c:45)
==25613== Uninitialised value was created by a stack allocation
==25613== at 0x400720: split (strutil.c:9)
几个类似的错误然后sigsem并关闭。我担心的是,当我用gdb运行它时,它应该用于计算''的圆,它会按预期旋转,直到它达到值'',然后跳过整个cicle,但是i ++继续前进。它为什么这样做?我观察了gdb,并且所有参数(str [i],sep)在条件之前都有正确的值。
#include "strutil.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char** split(const char* str, char sep){
size_t cant = 2;
size_t i;
for(i = 0; i < strlen(str); i++){//this is line 9
if(str[i] == sep)
cant ++;
i++;
}
size_t corte[cant];
i = 0;
corte[0] = 0;
size_t j = 1;
size_t cant_corte[cant];
for(i = 0; i < strlen(str); i++){
if(str[i] == sep){
corte[j] = i + 1;
cant_corte[j - 1] = corte[j] - corte[j - 1];
//printf("pasa\n");
j++;
}
printf("pasa\n");
i++;
}
char** strv = malloc(sizeof(char*) * cant);
if (strv == NULL)return NULL;
for(i=0; i < cant; i++){
strv[i] = malloc(sizeof(char) * cant_corte[i]);
if (strv[i] == NULL)return NULL;
strncpy(strv[i], str + corte[i], cant_corte[i-1]);
strcat(strv[i], "\0");
}
strv[cant + 2] = NULL;
return strv;
}
int main(){
char* eje = "abc,defg";
printf("%s\n", eje);
char r = ',';
char** prueba = split(eje, r);
printf("%s\n", prueba[0]);
getchar();
return 0;
}
答
如果你不想让你的i
可变继续增加,那么请确保您的循环,你不增加i
,而是取决于for循环来完成其工作。 (每次条件为真时递增i)。
+0
我疯了,事情是,我在forloop之前使用了一段时间,并没有改变我真的对不起浪费你的时间对不起 –
+0
不浪费我的时间,有时简单的错误是困难的。 –
'cant_corte [i-1]' - UB for i = 0 –
'strv [cant + 2] = NULL;':这发生在界限之外。 – BLUEPIXY
@ DavidC.Rankin什么? 'strv'是'malloc'的返回值,它肯定是可测试的。 '如果(* strv == NULL)'会有所不同,并且valgrind将会完全正确地抱怨。 – aschepler