C Programming - Segmentation fault on strcat


#1

C Heads,

I have recently begun working on learning the C language and have repeatedly run into an error in which calling the strcat function from the <string.h> module results in a segmentation fault. I've searched for the answers online, including on stackoverflow, without success. I thought this community might have a more personal insight into the problem, as the general solutions don't seem to be working.

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

char * deblank(const char str[]){
    char *new[strlen(str)];
    char *buffer = malloc(strlen(new)+1);
    for (int i=0; i<strlen(str); i++){
        if(buffer!=NULL){
            if(str[i]!=" "){
                strcat(new,str[i]); //Segmentation fault
            }
        }
    }
    free(buffer);
    return new;
}

int main(void){
    char str[] = "This has spaces in it.";
    char new[strlen(str)];
    *new = deblank(str);
    puts(new);
}

I've placed a comment on the line I've traced the segmentation fault back to. For comparison, I've also written a Java version of the program.

public class deblank {
	public static void main(String[]args){
		String str = "This has space in it.";
		System.out.println(removeBlanks(str));
	}
	
	public static String removeBlanks(String str){
		String updated = "";
		for(int i=0; i<str.length(); i++){
			if(str.charAt(i)!=' '){
				updated+=str.charAt(i);
			}
		}
		return updated;
	}
}

Any insights into this error will be much appreciated. Please point out typos as well... I've been known to make them. Thanks.


#2

After much (slightly insulting) conversation with some stackoverflow users... A result has emerged:

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

char * deblank(const char str[]) {
    char *buffer = malloc(strlen(str)+1); // allocate space to contains as much char as in str, included ending NUL byte
    for (int i=0, j=0; i<strlen(str)+1; i++) { // for every char in str, included the ending NUL byte
      if (str[i]!=' ') { // if not blank
        buffer[j++] = str[i]; // copy
      }
    }
    return buffer; // return a newly constructed C-string
}

int main(void){
    char str[] = "This has spaces in it.";
    char *new = deblank(str);
    puts(new);
    free(new); // release the allocated memory
}