Runtime error in c implementation but local fine


  • 0
    L
    void swap(char *a, char *b)
    {
    	*a ^= *b;
    	*b ^= *a;
    	*a ^= *b;
    }
    void reverse(char *str, int s, int t)
    {
    	int i = s, j = t;
    	while (i < j)
    		swap(&str[i++], &str[j--]);
    }
    char *compress(char *s)
    {
    	if (s == NULL)
    		return NULL;
    	int n = strlen(s);
    	char *d = malloc(sizeof(char) * n);
    	int i = 0;
    	int j = n - 1; 
    	while (isblank(s[i])) i++;
    	while (isblank(s[j])) j--;
    	int k = 0;
    	for (; i <= j; ++i) {
    		if (!isblank(s[i]) || (i > 0 && !isblank(s[i - 1]))) {
    			d[k++] = s[i];
    		}
    	}
    	d[k] = 0;
    	strcpy(s, d);
    	free(d);
    	return s;
    }
    void reverseWords(char *s)
    {
    	if (s == NULL)
    		return;
    	compress(s);
    	int n = strlen(s);
    	if (n <= 1)
    		return;
    	reverse(s, 0, n - 1);
    	int pos = 0;
    	for (int i = 0; i < n; ++i) {
    		if (isblank(s[i])) {
    			reverse(s, pos, i - 1);
    			pos = i + 1;
    		}
    	}
    	reverse(s, pos, n - 1); // The last word
    }
    
    // Runtime error ,
     The last input: "pz! .xwy.,cga. vua frjrmcjf, xxw'izz vgthvpfhl sldudifok wvls orujxroi w. oo c?ymxlptr ff'?rh bsjjoyjwvx tj pqv.zlq ,jlu',j dg izq.fo wtvwqn teual jnsv.a .oclyrvg tkgag'a' !wsz?sclc pvhl.ypq vyin cn?z,kxg , u l?l glr zf'hew l'wmi .nlvgr u zfwzra? ot!emgg. rg,'.d.kp fn vat ba.myfqxe znzdrhh xjeubr taztndst v nep?bs .,pwin. e pi"
    

    Run in my host is fine, So I don't know why !


  • 0
    W

    Here's the problem

    char *d = malloc(sizeof(char) * n);

    should be

    char *d = malloc(sizeof(char) * (n+1));

    need one more char for 0x00 for end of string;


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.