我有以下c
代码
void *curr = (unsigned long *)some_fixed_address;
if (!curr) {*(unsigned long *)curr = a^b;}
其中some_fixed_address
存储长整数0
,而a
和b
是一些预定义的整数。当我运行这段代码时,我得到一个错误
Program received signal SIGSEGV, Segmentation fault.
有什么可能的原因吗?
更新:
这是最小的可验证示例:
#include <stdio.h>
int main()
{
size_t start = 0;
size_t a = 5;
size_t b = 100;
void *curr = (char *)start;
if (!curr) {*(unsigned long *)curr = a^b;}
printf("%d", *(int *)curr);
return 0;
}
答案 0 :(得分:3)
在您的计算机上,NULL
可能与0
逐位相等(尽管标准不需要这样做)。
因此,当您将some_fixed_address
转换为指针时,最终将得到充满0
的指针,即NULL
指针。
!curr
然后检查curr
是NULL
。然后,您尝试在curr
语句的正文中取消引用if
,这将导致SEGFAULT。
答案 1 :(得分:2)
给出的唯一逻辑解释是@Controller
public class EmployeeController {
@RequestMapping(value = "/getEmployees", method = RequestMethod.GET)
public ModelAndView getEmployeeInfo() {
return new ModelAndView("getEmployees");
}
@RequestMapping(value = "/showEmployees", method = RequestMethod.GET)
public ModelAndView showEmployees(@RequestParam("code") String code) throws JsonProcessingException, IOException {
ResponseEntity<String> response = null;
System.out.println("Authorization Code------" + code);
RestTemplate restTemplate = new RestTemplate();
// According OAuth documentation we need to send the client id and secret key in the header for authentication
String credentials = "javainuse:secret";
String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.add("Authorization", "Basic " + encodedCredentials);
HttpEntity<String> request = new HttpEntity<String>(headers);
String access_token_url = "http://localhost:8080/oauth/token";
access_token_url += "?code=" + code;
access_token_url += "&grant_type=authorization_code";
access_token_url += "&redirect_uri=http://localhost:8090/showEmployees";
response = restTemplate.exchange(access_token_url, HttpMethod.POST, request, String.class);
System.out.println("Access Token Response ---------" + response.getBody());
return null;
}
}
为零,这是不可寻址的,因此是段错误。
您的some_fixed_address
否则无法执行-仅在if (!curr) { ... }
为curr
时执行 。
我想知道您的0
语句的逻辑是否倒退。 (或者您没有提供足够的信息,并且您的错误在其他地方。)
答案 2 :(得分:1)
这段代码没有意义
void *curr = (unsigned long *)some_fixed_address;
if (!curr) {*(unsigned long *)curr = a^b;} <<< only if curr is null then try to do something with it
我想你是说
void *curr = (unsigned long *)some_fixed_address;
if (curr) {*(unsigned long *)curr = a^b;} <<<< if curr is not null then try to do something
但是,您在该行上遇到错误的事实强烈表明some_fixed_address为0。因此,上面的“更正”代码将运行,但不会执行任何操作。