[英]String concatenation in C
所以我得到了這個函數,如果沒有空間,該函數可以在“ /” C前面放置一個空格。 並且它可以減少字符串,但是當我嘗試將字符串連接在一起時,我收到錯誤,可能是內存違規。 請幫幫忙。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* substr(const char *pstr, int start, int numchars) {
char* pnew = malloc(numchars + 1);
strncpy(pnew, pstr + start, numchars);
pnew[numchars] = '\0';
return pnew;
}
char* fixString(char str[]) {
char* position;
char* newString = "";
char* finalString;
int oldPosition = 0;
printf("Original str: %s\n", str);
printf("Original length: %d\n\n", strlen(str));
position = strchr(str, '/');
while (position != NULL) {
int charPosition = position - str;
printf("String position: %d->%d\n", oldPosition, charPosition);
newString = substr(str, oldPosition, charPosition - oldPosition);
oldPosition = charPosition;
if (charPosition > 0 && str[charPosition - 1] != ' ') {
printf("Previous char: %c\n", str[charPosition - 1]);
newString = strcat(newString, " ");
}
printf("String: |%s|\n", newString);
if (strlen(newString) > 0) {
finalString[0] = strcat(finalString, newString);
}
printf("------------\n");
position = strchr(position + 1, '/');
}
char* lastString = substr(str, oldPosition, strlen(str));
finalString = strcat(finalString, lastString);
printf("lastString: %s\n\n", lastString);
return finalString;
}
int main() {
char* testString = "/Filter /FlateDecode/Length 7108/Subtype /Type1C";
printf("%s", fixString(testString));
return 0;
}
您永遠不會分配目標緩沖區。 finalString
變量未初始化為任何東西。
這也不是代碼的唯一問題。 您似乎將char *
視為某種智能字符串類型,但它不過是指向內存位置的指針。 例如,這個:
newString = strcat(newString, " ");
不連接兩個字符串並返回連接結果。 它在char緩沖區中追加一個空格,newString指向並返回相同的緩沖區。 分配給newString是無害的,但具有誤導性。
// It is the callers responsibility to free the returned string.
char *fixString(char *str) {
int len;
char *s;
char *dest;
int after_space;
// First pass, figure out the size of the output.
len = 0;
after_space = 0;
for (s = str; *s; s++) {
len += 1 + (!after_space && *s == '/');
after_space = *s == ' ';
}
dest = malloc(len + 1);
s = dest;
after_space = 0;
while(*str) {
if (!after_space && *str == '/') *s++ = ' ';
after_space = (*s++ = *str++) == ' ';
}
return dest;
}
你需要為finalString
分配一些內存。
嘗試這樣做:
#define BUFFER_SIZE 1024
char* finalString = malloc(BUFFER_SIZE);
// ...
strncat(finalString, "something", 1024);
記得在你不再需要它時調用指針上的free()
(不是在你的函數中 - 在函數返回之后,在客戶端代碼中的某個地方,只要不需要結果)。
你永遠不malloc
內存為您newString
和finalString
指針。 strcat
期望你給它的目標指針有足夠的空間來存儲字符串。
必要時,您可能還必須檢查malloc()和realloc()之后的大小。 歡迎來到美麗的C語言內存管理世界:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.