我在为面试做编码挑战。获取此错误:
Reading symbols from Solution...done.
[New LWP 183007]
Core was generated by `./Solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x00007fb1eb4fdcf8 in ?? ()
字符串
守则如下:
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
/*
* Complete the 'newPassword' function below.
*
* The function is expected to return a STRING.
* The function accepts following parameters:
* 1. STRING a
* 2. STRING b
*/
/*
* To return the string from the function, you should either do static allocation or dynamic allocation
*
* For example,
* char* return_string_using_static_allocation() {
* static char s[] = "static allocation of string";
*
* return s;
* }
*
* char* return_string_using_dynamic_allocation() {
* char* s = malloc(100 * sizeof(char));
*
* s = "dynamic allocation of string";
*
* return s;
* }
*
*/
char* newPassword(char* a, char* b) {
int len = strlen(a);
char* c = "";
int i = 0;
for(; i < len; i++){
strcat(c, &a[i]);
strcat(c, &b[i]);
}
for(int z = i; z < strlen(b); z++){
strcat(c, &b[z]);
}
return c;
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char* a = readline();
char* b = readline();
char* result = newPassword(a, b);
fprintf(fptr, "%s\n", result);
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\0';
break;
}
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
data = realloc(data, data_length);
if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
型
我不是一个真正的C/C++的人,所以需要一些见解。
1条答案
按热度按时间o2gm4chl1#
第一个循环的边界不正确。如果
a
的长度比b
的长度长,则会存取b
结尾以外的字符。你应该有三个循环。1.第一个循环的次数与两个长度中较小者的次数相同。
1.第二个循环在
a
超过b
的字符上循环。1.第三个循环在
b
超过a
的字符上循环。在C语言中,所有的字符串,包括空字符串
""
,实际上都是字符数组。空字符串是一个由一个字符(空终止符)组成的数组。不允许修改这些数组。任何修改此类数组的尝试都会导致未定义的行为。这就是为什么在使用指向文本字符串的指针时,建议使用const char *
。方便地,我们知道新密码的长度将是
strlen(a) + strlen(b)
个字符。我们把它叫做n
。这意味着你需要一个n+1
个字符的数组。(+1
用于NUL。)使用char c[n+1];
不可行,因为您希望数组存在于函数末尾之外(因为您要返回它)。因此,您需要使用char *c = malloc(n+1);
。然后是
strcat
的误用。两个参数都应该是(以NULL结尾)字串。如果a
是UVW
,而b
是xyz
,则您要建置的是UVWxyzVWyzWz
,而不是UxVyWz
。要添加一个字符,由于您已经有足够的内存(在上面的修复之后),您可以直接将赋值给数组中正确的元素。别忘了用NUL终止它。记:第二节第一段是Some programmer dude写的。