简体   繁体   中英

malloc() returns a pointer to char full of random characters

I have a simple program in C and I'm trying to make the intersection of two sets(no duplicates). And there are a bunch of characters printed after my intersection result.

It's some how related to the fact that strlen(scommon) = 14 instead of 2(sizeof(char) * strlen(smin) = 1 *2).

Thanks.

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* intersection(char *s1, char *s2);

int main(void){


   printf("intersection = %s\n", intersection("ag", "cg"));

   return 0;
}

char* intersection(char *s1, char *s2){
    int i, j;
    char *smin, *scommon;   

    if(strlen(s1) < strlen(s2)){    
        smin = s1; 
        s1 = s2;
    }else{      
        smin = s2;      
    }

    scommon = (char*)malloc(sizeof(char) * strlen(smin));   

    for(i = 0; i < strlen(smin); i++){

        for(j = 0; j < strlen(s1); j++){

            if(smin[i] == s1[j]){

                scommon[i] = smin[i];

                break;
            }
        }
    }

    printf("final length = %d\n", strlen(scommon));     
    return scommon;
}

在此处输入图片说明

You forgot to null-terminate your scommon string. You have to add a '\\0' after the last character, or the strlen and printf will just keep going until they hit a null character, or crash the program.

In general, you cannot count on malloc to return buffers with all 0's in them. If you want the buffer to be 'empty' you have to initialize it yourself, or use calloc instead

scommon = (char*)malloc(sizeof(char) * strlen(smin));

This doesn't add an extra byte to accommodate a null terminator for the string, and intersection doesn't add a null terminator after the loop completes.

You could just change it to:

scommon = malloc(strlen(smin)+1);
memset( scommon, 0, strlen(smin)+1 );

Or add the terminating zero when the loop completes and you know where you want to put it.

Or just use calloc which will initialize the buffer for you:

scommon = calloc(strlen(smin)+1, sizeof(char));

I guess the main issue is (apart from the null termination issue):

scommon[i] = smin[i];

If there is not an intersection then i will be increased none-the-less. And according to the malloc function description:

The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.

You should use a separate counter for scommon . And add a null termination character or save the length of the string somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM