我正在尝试编写一个将字符串拆分为多个字符串的函数,我知道我有很多分配的空间未释放,我只是测试这一点,但 valgrind 显示了我
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 并关闭。我担心的是,当我在 for 循环中使用 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
变量继续递增,请确保在 for 循环中不递增 i
,而是依赖于 for 循环做它的工作。 (每次条件为真时增加 i )。
关于c - 为什么我的程序跳过 for 循环? C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46677350/