[英]When I run my program I get the 'Segmentation fault 11' error. I'm not sure what in my code would cause this error
I understand that this error has to do with how much memory my program tries to use when I run it, but I'm new to C and I don't quite have a handle on memory management yet.我知道这个错误与我的程序在运行时尝试使用多少内存有关,但我是 C 的新手,我还不太了解内存管理。 If anyone wants to take the time to tell me where in my code this is occurring I would very much appreciate it.如果有人想花时间告诉我这发生在我的代码中的哪个位置,我将非常感激。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
char * getRandomHex(int length, char * result) {
char hexCharacters[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
for (int i = 0; i < length; i++) {
char randChar = hexCharacters[rand()%16];
strncat(result, &randChar, 1);
}
return result;
}
int main() {
for (int i = 0; i < 10; i++) {
char * result;
result = getRandomHex(6, result);
printf("%s", result);
printf("\n");
}
}
The first 3 of these are the main issues:其中前 3 个是主要问题:
main()
: allocate space for result. main()
:为结果分配空间。getRandomHex()
assign to result[i]
instead of using strncat()
incorrectly. getRandomHex()
分配给result[i]
而不是错误地使用strncat()
。getRandomHex()
: don't assume that result
argument contains a terminating '\0'. getRandomHex()
:不要假设result
参数包含终止 '\0'。getRandomHex()
using a string as it's easier to write. getRandomHex()
使用字符串,因为它更容易编写。 Making it static const
as it read-only.使其成为static const
,因为它是只读的。LEN
instead of the magic number 6.定义LEN
而不是幻数 6。hexCharacters()
instead of hard-coding it to 16
. hexCharacters()
的派生大小,而不是将其硬编码为16
。result
variable).结合两个打印语句,并使用返回值(即result
变量)。#include <stdio.h>
#include <stdlib.h>
#define LEN 6
// caller must allocate result array of size at least length + 1 bytes
char *getRandomHex(int length, char *result) {
static const char hexCharacters[] = "0123456789ABCDEF";
for (int i = 0; i < length; i++) {
result[i] = hexCharacters[rand() % (sizeof(hexCharacters) - 1)];
}
result[length] = '\0';
return result;
}
int main() {
char result[LEN + 1];
for (int i = 0; i < 10; i++) {
printf("%s\n", getRandomHex(LEN, result));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.