1

我有一个在 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]);
}
4

1 回答 1

2

You are not calculating the malloc() size correctly at all. You need to use two loops, one to calculate the size, then another to copy the strings after allocating the memory:

int lastidx = i-1;

int size = strlen(argv[0]) + 1;
for (int idx = 1; idx < lastidx; ++idx) {
    size += (1 + strlen(argv[idx]));
}

histL[count-1] = (char*) malloc(size);

strcpy(histL[count-1], argv[0]);
for (int idx = 1; idx < lastidx; ++idx) {
    strcat(histL[count-1], " ");
    strcat(histL[count-1], argv[idx]);
}

Or better:

int lastidx = i-1;

int size = strlen(argv[0]) + 1;
for (int idx = 1; idx < lastidx; ++idx) {
    size += (1 + strlen(argv[idx]));
}

char *str = (char*) malloc(size);

int len = strlen(argv[0]);
memcpy(str, argv[0], len);
size = len;

for (int idx = 1; idx < lastidx; ++idx) {
    str[size++] = ' ';
    len = strlen(argv[idx]);
    memcpy(str+size, argv[idx], len);
    size += len;
}

str[size] = '\0';
histL[count-1] = str;
于 2014-12-11T04:39:47.057 回答