我有一个在 valgrind 中写入无效的代码。我试图做的是strcat我malloc'd的idx。我想知道 strdup() 的大小,以便我可以在 char *argv[] 中的标记数之间放置空格。
这是一小段代码
如果您对如何从 getline 收集令牌的大图感兴趣,您可以在此处查看问题https://stackoverflow.com/questions/27394313/getline-loop-for-stdin-has-segmentatoin-fault-after-每个循环-c
// parent will wait for child to exit
id = wait( &status );
if( id < 0 ) {
perror( "wait" );
} else {
int idx = 0;
histL[count-1] = strdup(argv[idx]);
//printf("Token added %s size of %i is\n", argv[idx], i);
for (idx = 1; idx < i-1; idx++) { //-1 because no need last one
strcat( histL[count-1], " ");
strcat( histL[count-1], argv[idx]);
//printf("Token added %s\n", argv[idx]);
}
//printf("Exit for Loop\n");
//puts( "Parent is now exiting." );
//exit( EXIT_SUCCESS );
}
这是我目前能做的最好的
int idx = 0;
histL[count-1] = ( char* )malloc( sizeof( argv ) + (i*sizeof(" ")));// histLSize ); //strdup(argv[idx]);
strcpy(histL[count-1], strdup(argv[idx]));
//printf("Token added %s size of %i is\n", argv[idx], i);
for (idx = 1; idx < i-1; idx++) { //-1 because no need last one
histL[count-1] = strcat( histL[count-1], " ");
histL[count-1] = strcat( histL[count-1], argv[idx]);
//printf("Token added %s\n", argv[idx]);
}
解决它
int idx = 0;
histL[count-1] = ( char* )malloc( sizeof( &argv ) + (i*sizeof(" ")));// histLSize ); //strdup(argv[idx]);
strcpy(histL[count-1], argv[idx]);
//printf("Token added %s size of %i is\n", argv[idx], i);
for (idx = 1; idx < i-1; idx++) { //-1 because no need last one
histL[count-1] = strcat( histL[count-1], " ");
histL[count-1] = strcat( histL[count-1], argv[idx]);
//printf("Token added %s\n", argv[idx]);
}